php - PDO 查询返回空

标签 php mysql pdo

我有一个连接类文件,它允许我的其他类“函数”连接到我的 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/

相关文章:

javascript - 如何删除数组中的数组? json 的 AJAX 数据

mysql - MySQL 不支持哪些 SQL Server 查询语法?

MySQL 创建/删除用户返回 0

php - 两个数据库上的两个事务

php - 如何在服务器端脚本可以访问的同时将敏感数据安全地存储在共享主机提供商上?

php - 更改 mysql 列名称以与 FPutCSV() 一起使用

mysql - 将数据从一个数据库复制到同一个表中的另一个数据库

php - 如何将查询的第一个结果与其余结果分开?

php - PDO:如何用数据库表中的行填充html表?

php 从字符串中获取数字