2013-12-20 179 views
0

我有一个连接类文件,它允许我的其他类“函数”连接到我的MySQL数据库。但是,当我执行MySQL查询时,它仅返回Array()。我选择的数据其实就在那里(我查过)。问题是什么?PDO查询返回空

Connection.php

<?php 

class Connection extends PDO { 

private $username; 
private $password; 
private $database; 
private $hostname; 

public function __construct($hostname, $username, $password, $database) { 

    $this->hostname = $hostname; 
    $this->username = $username; 
    $this->password = $password; 
    $this->hostname = $hostname; 

    try { 
     parent::__construct("mysql:host=" . $this->hostname . ";dbname=" . $this->database, $this->username, $this->password); 
    } 

    catch (PDOException $e) { 
     echo $e->getMessage(); 
    } 
    } 
} 

?> 

的functions.php

<?php 

require_once "Connection.php"; 

class Functions { 

private $connection; 

public function __construct() { 
    $this->connection = new Connection("127.0.0.1", "xxx", "xxx", "xxx"); 
} 

public function sqlFetchAssoc($query) { 

    $sth = $this->connection->prepare($query); 
    $sth->execute(); 
    $result = $sth->fetchAll(PDO::FETCH_ASSOC); 

    return $result; 
    } 
} 

$functions = new Functions(); 
$row = $functions->sqlFetchAssoc("SELECT * FROM chatlogs WHERE id = 70"); 

print_r($row); 

?> 
+0

你应该在那里添加更多的错误检查。看看你是否在某处发生错误。 –

+1

你为什么不直接使用PDO对象呢? –

+0

http://www.php.net/manual/en/pdo.errorinfo.php –

回答

0

我发现你在Connection.php错误:

$this->hostname = $hostname; 
$this->username = $username; 
$this->password = $password; 
$this->hostname = $hostname; 

$this->hostname重复$this->database未设置。但是,您可以完全剥离设置$this->something,因为您在相同的功能中使用这些值。这将使它更简单:

try { 
    parent::__construct("mysql:host=" . $hostname . ";dbname=" . $database, $username, $password); 
} 

我建议更进一步。你应该分别测试测试。您可以在testfunction.php写这个剧本并调试它(如果需要):

<?php 
class Functions { 
private $connection; 

public function __construct() { 
    $this->connection = new PDO("mysql:host=127.0.0.1;dbname=xxx", "xxx", "xxx"); 
} 

public function sqlFetchAssoc($query) { 

    $sth = $this->connection->prepare($query); 
    $sth->execute(); 
    $result = $sth->fetchAll(PDO::FETCH_ASSOC); 

    return $result; 
    } 
} 

echo "Test started <br><br>"; 
echo "Initialization: <br>"; 
$functions = new Functions(); 
echo "Correct<br><br>"; 
echo "Performing a select: <br>"; 
$row = $functions->sqlFetchAssoc("SELECT * FROM chatlogs WHERE id = 70"); 
print_r($row); 
echo "Test finished."; 
?> 

然后做一流的类似的东西。那么不仅可以更容易地发现错误,而且如果发生错误,您可以参加这些测试,看看出了什么问题,而不是再次写出错误。切记不要将它们包含在生产代码中。

+1

确实非常尴尬的错误!这似乎解决了它。非常感谢。 – user2879373

+1

如果你打算重用这段代码,我还建议默认设置'charset = utf8'。别客气 (: –