我有一个连接类文件,它允许我的其他类“函数”连接到我的 MySQL 数据库。但是,当我执行 MySQL 查询时,它仅返回 Array () 。事实上,我选择的数据就在那里(我检查过)。可能是什么问题?
连接.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();
}
}
}
?>
函数.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);
?>
最佳答案
我刚刚在 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.";
?>
然后对第一个类做类似的事情。这样不仅会更容易发现错误,而且如果发生错误,您可以通过这些测试来查看出了什么问题,而不用重新编写它们。请记住不要将它们包含在生产代码中。
关于php - PDO 查询返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20712029/