我将预设的语句设置为阻止SQL注入,定义为:
if($stmt1 = $db->prepare("INSERT INTO `group_messages`(`group_message_sync_id`, `from_user_sync_id`, `to_user_sync_id`, `to_group_sync_id`, `sent_dt`, `read`, `read_dt`, `message_text`, `shared_campaign_id`, `shared_campaign_location_id`)
SELECT
(SELECT
CASE WHEN
max(group_message_sync_id) is null
then 0
else max(group_message_sync_id)
end + 1
from group_messages)
, ?
, b.user_sync_id
, b.group_sync_id
, NOW()
, 0
, 0
, ?
, ?
, ?
from users_groups b
WHERE
b.status = 1
and b.group_sync_id = ?
and b.user_sync_id != '?;"))
{
$stmt1->bind_params("ssssss",$userId,$message,$campaign,$location,$toGroupId,$userId);
$stmt1->execute();
$stmt1->close();
如您所见,我将6个参数传递给此声明
但是,每次围绕此语句的if-else子句都会失败。
我怎样才能让它发挥作用?
答案 0 :(得分:1)
您查询中的错误是'
中有b.user_sync_id != '?;
您必须将其更改为:b.user_sync_id != ?;
关于报告错误的评论中的问题,最好的办法是使用exceptions:
$db = new PDO('<params>');
//this will make PDO throws exceptions in case of errors
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try
{
$stmt1 = $db->prepare('<your query>');
$stmt1->execute();
}
catch (PDOException $e)
{
//here you handle the exception, i.e die and show the message
die( PDO Exception: ' . $e->getMessage() );
}
这样,当发生语法错误时,PDO将启动PDOException
语句捕获的catch
。例如,在语句中,您可以打印异常消息。