我只是尝试PDO并且我得到了这个错误,致命错误:在非对象上调用成员函数fetch(),但是它不是已经在$ this-> db对象上了吗?
class shoutbox {
private $db;
function __construct($dbname, $username, $password, $host = "localhost" )
{ # db conections
try {
$this->db = new PDO("mysql:host=".$hostname.";dbname=".$dbname, $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
function getShouts()
{
$sql_shouts = $this->db->query('SELECT shoutid, message, pmuserid, ipadress, time FROM shouts WHERE pmuserid == 0');
return $sql_shouts->fetch(PDO::FETCH_OBJ);
}
}
Run Code Online (Sandbox Code Playgroud)
tim*_*dev 17
仔细查看PDO :: query的文档,特别是"返回值"部分:
PDO :: query()返回PDOStatement对象,失败时返回FALSE.
重要的是"失败时假".FALSE不是一个对象,所以调用 - > fetch()是坏消息.
该错误可能是由于您使用"=="比较运算符.在SQL中,它只是"=".
你应该测试$sql_shouts不是假的,然后做一些聪明的错误,如果有的话:
<?PHP
$sql_shouts = $this->db->query('...');
if ($sql_shouts === false){
$errorInfo = $this->db->errorInfo();
//log the error or take some other smart action
}
return $sql_shouts->fetch(PDO::FETCH_OBJ);
Run Code Online (Sandbox Code Playgroud)
我想说的是,由于语法不正确,您的查询未执行。您确实应该检查 PDO 的 errorinfo 静态函数以查看查询是否出错。
这是一个可能正确的 SQL 语句:
$sql_shouts = $this->db->query('SELECT shoutid, message, pmuserid, ipadress, `time` FROM shouts WHERE pmuserid = 0');Run Code Online (Sandbox Code Playgroud)
我相信时间是 MySQL 中的保留字,我建议使用不同的名称,但用反引号括起来可以缓解这个问题。1个等号用于mysql,而不是两个。但是,是的,请查看 errorinfo 函数以确定您的查询是否由于语法错误而失败并妥善处理。
| 归档时间: |
|
| 查看次数: |
41178 次 |
| 最近记录: |