PHP PDO选择查询无返回值

时间:2018-10-18 17:57:57

标签: php select pdo

connection.php

<?php

class DBConnection
{

    private $servername;
    private $username;
    private $password;
    private $dbname;

    private $conn;

    public function __construct()
    {

        $this->servername   = "localhost";
        $this->username     = "root";
        $this->password     = "";
        $this->dbname       = "pdo_test";
        try {
            $this->conn = new PDO("mysql:host=$this->servername;dbname=$this->dbname", $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            echo "connected successfully";
        }catch(PDOException $e){
            echo "Error: " . $e->getMessage();
        }
    }
}
?>

insert.php

<?php 
include('connection.php');

class insertData extends DBConnection
{
    private $conn;

    public function __construct()
    {
        $this->conn = new DBConnection();
    }

    public function getData()
    {
        $sql = "SELECT * FROM user";
        $stmt = $this->conn->prepare($sql);
        $res = $stmt->execute();
        print_r($res->fetch());
    }
}

$id = new insertData();
echo $id->getData();

?>

我已经在connection.php中创建了数据库连接,并将其包含在insert.php中。然后在构造函数中扩展类DBConnection类,然后创建一个函数getData(),在我运行文件时在其中运行选择查询,仅获得连接成功消息。我尝试了所有可能的选项,并在stackoverflow和其他地方搜索了解决方案,但失败了。

有人可以指出我的代码错误吗?预先感谢

注意:尽管没有任何联系,但仍然需要更多信息,我正在使用Ubuntu 18.04

1 个答案:

答案 0 :(得分:2)

尽管我认为您的类层次结构不正确,但问题是在您的insertData类中,您有一个构造函数来创建DBConnection实例并将其分配给$this->conn。因此,当您引用$this->conn时,是指DBConnection实例,而不是PDO对象。所以您打给

$stmt = $this->conn->prepare($sql);

将失败,因为DBConnection没有prepare()方法。

相反,如果您删除构造函数并将其留给基类,则将创建连接并将其分配给$this->conn。您必须更改的一件事是$conn必须定义为protected才能允许派生类访问它。

protected $conn;

还要确保当您执行execute()时,如果执行成功,则返回fetch()

class insertData extends DBConnection
{
    public function getData()
    {
        $sql = "SELECT * FROM user";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute();
        $res = $stmt->fetch();
        print_r($res);
    }
}

更新

要检查发生了什么,可以尝试...

ini_set('display_errors', 'On');
error_reporting(E_ALL);
$id = new insertData();
echo $id->getData();