我有一个Connection类文件,它允许我的其他类“Functions”连接到我的MySQL数据库。但是,当我执行MySQL查询时,它只返回Array ()
。事实上,我选择的数据是(我检查过)。问题是什么?
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 :(得分: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.";
?>
然后为第一堂课做类似的事情。然后不仅会更容易发现错误,但如果发生错误,您可以参加这些测试,看看出了什么问题,而不是再次写出来。切记不要将它们包含在生产代码中。