php mysql绑定param参数

时间:2014-10-10 20:00:21

标签: php mysql mysqli sqlbindparameter

我第一次尝试使用预准备语句,并使用以下代码

遇到以下问题

错误:

  

警告:mysqli_stmt_bind_param()期望参数1为   mysqli_stmt,给定布尔值

代码:

 $stmt = mysqli_prepare($db, "INSERT INTO fragrances(name, description, essentialoils, topnotes, middlenotes, basenotes, reference, year, type, price, fragrancehouse, triangle, extractname, extractreference, extractprice, extractfragrancehouse, disccolour, collarcolour, actuatorcolour)
    VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); 
            mysqli_stmt_bind_param($stmt, 'sssssssssssssssssss', $name, $description, $essentialoils, $topnotes, $middlenotes, $basenotes, $reference, $year, $type, $price, $fragrancehouse, $triangle, $extractname, $extractreference, $extractprice, $extractfragrancehouse, $disccolour, $collarcolour, $actuatorcolour);

         mysqli_stmt_execute($stmt); 

我在这里看了很多不同的问题,他们的解决方案似乎都没有适用于我的问题,有谁知道问题是什么?

请注意,我的所有变量都是字符串

由于

4 个答案:

答案 0 :(得分:4)

仅当$stmt返回false时,

mysqli_prepare才成为布尔值。

当发生这种情况时,意味着它无法准备查询,因此您需要检查错误:

$stmt = mysqli_stmt_init($db);
if (mysqli_stmt_prepare($stmt, 'INSERT INTO fragrances VALUES...')) {
    //it's all good bind and execute here
}else{
   //we have a problem
   printf("Errormessage: %s\n", mysqli_error($db));
}

答案 1 :(得分:2)

错误消息表示您的mysqli_prepare返回了一个布尔值(对于您的情况,它返回了false)。

您需要用字符?替换所有字段名称以制作准备好的语句。这是它的工作原理。

See example in the official documentation

编辑 See also mysqli_error,它会详细说明您的错误。实际上,在使用之前应始终检查变量:

$stmt = mysqli_prepare($db, "....");
if(!$stmt)
  echo mysqli_error($db); // display error only for debug. Avoid this in production

答案 2 :(得分:2)

您的INSERT语句无效:VALUES子句必须在括号中带有?(并在括号中的字段名称后面)。同样好的做法是在分配后检查$stmt

$stmt = mysqli_prepare($db, 
   "INSERT INTO fragrances (name, description, essentialoils, topnotes, middlenotes, basenotes, reference, year, type, price, fragrancehouse, triangle, extractname, extractreference, extractprice, extractfragrancehouse, disccolour, collarcolour, actuatorcolour)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
if ($stmt) {
    mysqli_stmt_bind_param($stmt, 'sssssssssssssssssss', $name, $description, $essentialoils, $topnotes, $middlenotes, $basenotes, $reference, $year, $type, $price, $fragrancehouse, $triangle, $extractname, $extractreference, $extractprice, $extractfragrancehouse, $disccolour, $collarcolour, $actuatorcolour);

    mysqli_stmt_execute($stmt);
    // ...
} else
    printf("Error: %s\n", mysqli_error($db));

答案 3 :(得分:2)

这意味着您的SQL无效,因为prepare返回false;

你的SQL应该是;

$stmt = mysqli_prepare($db, "INSERT INTO fragrances VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )");

每个?用于显示每个参数需要分别绑定的位置。