[英]PHP PDO CRUD class Call to a member function rowCount() on a non-object
I'm just getting started using PDO to move away from mysqli but hit a problem. 我刚开始使用PDO脱离mysqli,但是遇到了问题。 I'm following a tutorial and I want to return an array from the database but I get the following error:
我正在学习一个教程,我想从数据库中返回一个数组,但是出现以下错误:
Fatal error: Call to a member function rowCount() on a non-object in C:\\xampp\\htdocs\\phptuts\\crud\\core\\managedb.class.php on line 27 致命错误:在第27行的C:\\ xampp \\ htdocs \\ phptuts \\ crud \\ core \\ managedb.class.php中的非对象上调用成员函数rowCount()
Here is my managedb.php class: 这是我的managedb.php类:
<?php
class ManageDatabase
{
public $link;
function __construct()
{
include_once('database.class.php');
$conn = new database;
$this->link = $conn->connect();
return $this->link;
}
function getData($table_name, $id=null)
{
if(isset($id))
{
$query = $this->link->query("SELECT * FROM $table_name WHERE id = '$id' ORDER BY id ASC");
}
else
{
$query = $this->link->query("SELECT * FROM $table_name ORDER BY id ASC");
}
$rowCount = $query->rowCount();
if($rowCount >= 1)
{
$result = $query->fetchAll();
}
else
{
$result = 0;
}
return $result;
}
}
Then I'm simply using the following code to try and get a response: 然后,我只是使用以下代码来尝试获得响应:
<?php
include_once('../core/managedb.class.php');
$init = new ManageDatabase;
$table_name = 'users';
$data = $init->getData($table_name);
print_r($data);
This is when I get the error, Any ideas? 这是当我收到错误消息时,有什么想法吗?
I'd var_dump($query)
before the $rowCount = $query->rowCount();
我会在
$rowCount = $query->rowCount();
之前输入var_dump($query)
$rowCount = $query->rowCount();
line to see what it actually is, because apparently it's not an object. 行,看看它实际上是什么,因为它显然不是对象。 I'm guessing it's either NULL or empty because the whole
$this-link->query(<sql statement>);
我猜它为NULL或为空,因为整个
$this-link->query(<sql statement>);
didn't return what you expected 没有返回您的期望
A couple of things to check out: 需要检查的几件事:
From the PHP manual : 从PHP手册 :
PDO::query() returns a PDOStatement object, or FALSE on failure.
PDO :: query()返回PDOStatement对象,如果失败则返回FALSE。
You'll want to test if the query succeed and if not, why. 您将要测试查询是否成功,如果失败,为什么。 You can check the error using PDO's
errorInfo
function: 您可以使用PDO的
errorInfo
函数检查错误:
if ($query == false)
{
print_r($this->link->errorInfo());
exit();
}
Another thing to note is that rowCount()
in PDO returns the affected rows from a INSERT / UPDATE / DELETE type statement. 要注意的另一件事是PDO中的
rowCount()
从INSERT / UPDATE / DELETE类型的语句返回受影响的行。 For a SELECT you may get a row count, or you may not. 对于SELECT,您可能会获得行计数,否则可能不会。 The manual suggests a separate query to find the number of rows, but in your instance it might be easier testing if you get anything back from fetchAll():
该手册建议使用一个单独的查询来查找行数,但是在您的实例中,如果您从fetchAll()返回任何内容,则可能更容易测试:
$result = $query->fetchAll();
if (!empty($result))
{
return $result;
}
else
{
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.