为什么这个准备好的语句会抛出错误?

时间:2013-12-19 11:12:19

标签: php mysql

在学习了PHP和MySQL的基础知识之后,我现在正在学习如何使用预准备语句来防止SQL注入攻击。我有以下代码:

for ($i = 0; $i < $delegateno ;$i++){

        $q = "INSERT INTO delegates (delegate_id,booker_name, booker_email, booker_tel, booker_company, delegate_name, delegate_email, delegate_tel) VALUES (NULL, ?, ?, ?, ?, ?, ?, ? )";//Insert delegate information into delegate tables
        $stmt = mysqli_query($dbc, $q);
        mysqli_stmt_bind_param($stmt,'sssssss', $fullname, $email, $tel, $company,$delegatename[$i],$delegateemail[$i],$delegatetel[$i]);
        mysqli_stmt_execute($stmt);
}

但是,这会引发:

Notice: Query: INSERT INTO delegates (delegate_id,booker_name, booker_email, booker_tel, booker_company, delegate_name, delegate_email, delegate_tel) VALUES (NULL, ?, ?, ?, ?, ?, ?, ? )
MySQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?, ?, ?, ?, ? )'

我做错了什么?

1 个答案:

答案 0 :(得分:5)

因为您正在执行包含占位符的原始查询。您需要先prepare()查询。

这是通常的方式:prepare - &gt; bind_param - &gt; execute - &gt; fetch

变化:

$stmt = mysqli_query($dbc, $q);

为:

$stmt = mysqli_prepare($dbc, $q);