查询适用于Sequel Pro但不适用于我的PHP脚本

时间:2015-09-09 02:11:22

标签: php mysql sql mysqli sequelpro

此查询在Sequel Pro上运行正常:

SELECT t1.* FROM `erapido_messages` t1
LEFT OUTER JOIN `erapido_messages` t2 ON `t1.sender_id` = `t2.sender_id` 
AND (`t1.msg_date` < `t2.msg_date` OR `t1.msg_date` = `t2.msg_date` AND `t1.sender_id` != `t2.sender_id`)
WHERE `t2.sender_id` IS NULL AND `t1.sender_id`!= `0` AND `t1.receiver_id`= 28
ORDER BY `t1.msg_date` DESC;

当我在我的php脚本上使用它时会返回错误。这是php中的完整查询:

$query = "SELECT t1.* FROM `erapido_messages` t1
LEFT OUTER JOIN `erapido_messages` t2 ON `t1.sender_id` = `t2.sender_id` 
AND (`t1.msg_date` < `t2.msg_date` OR `t1.msg_date` = `t2.msg_date` AND `t1.sender_id` != `t2.sender_id`)
WHERE `t2.sender_id` IS NULL AND `t1.sender_id`!= `0` AND `t1.receiver_id`= ?
ORDER BY `t1.msg_date` DESC";

//$sql is my connection and it works fine on other queries
$statement = $sql->prepare($query);

//bind parameters for markers: s = string, i = integer, d = double,  b = blob
$statement->bind_param('i', $receiver_id);//$receiver_id is defined

//execute query
$statement->execute();

//store the results; allows to count the rows
$statement->store_result();

//bind result variables
$statement->bind_result($id, $receiver_name, $receiver_img, $receiver_email, $sender_id, $sender_name, $sender_email, $sender_img, $subject, $message, $msg_date);

这是错误:

Fatal error: Call to a member function bind_param() on boolean in /messages.php on line 53

据我所知,如果查询失败,此语句可能会返回'false':

$statement = $sql->prepare($query);

但是,我看不出查询中有什么问题。欢迎任何帮助!

非常感谢。

1 个答案:

答案 0 :(得分:-2)

由于查询字符串无效,您的prepare语句返回false。更改您的查询,如下所示。目前,您正在转义列名称,因为它们处于后退状态,这会在准备时导致错误

$query = "select * from `dbname` table where `table`.column= ?
          ORDER BY `table`.column DESC LIMIT 2 ";

这应该可以解决这个错误。