设置和执行准备好的语句(使用mysqli)

时间:2013-07-28 13:09:13

标签: php mysql forms mysqli prepared-statement

我在尝试运行这个mysql query / prepared语句时遇到了问题。

  <?php

  if (!empty($_POST['var1'])&&!empty($_POST['var2'])
    &&!empty($_POST['var3'])&&isset($_POST['var4'], 
    $_POST['var5'], $_POST['var6'])) {

  require_once 'connect.inc.php'; 

  $query = "INSERT INTO tablename (var1, var2, var3, var4, var5, var6)
  VALUES (?,?,?,?,?,?)";

  $stmt = mysqli_prepare($link, $query);

  mysqli_stmt_bind_param($stmt, "ssssss", $var1, $var2, $var3, $var4, $var5, $var6);

  $var1 = $_POST['var1'];
  $var2 = $_POST['var2'];
  $var3 = $_POST['var3'];
  $var4 = $_POST['var4'];
  $var5 = $_POST['var5'];
  $var6 = $_POST['var6'];

  mysqli_stmt_execute($stmt);

   if (mysqli_stmt_affected_rows($stmt)==1) {
   echo 'Thank you for your submission.';
      } else {
      mysqli_stmt_close($stmt);
      mysqli_close($link);  }

 } else {
echo 'We were unable to process your information. Please ensure all required fields 
        were filled out.'.mysqli_stmt_error($stmt);
} 

?>

当我运行代码时,收到以下错误消息:

 Notice: Undefined variable: stmt in ...on line 62
  Warning: mysqli_stmt_error() expects parameter 1 to be mysqli_stmt, null given in ... on        line 62

第62行是最后包含mysqli_stmt_error($stmt)的行。据我所知,我已正确设置$stmt。 ($link来自connect.inc.php页面。)我不确定为什么我收到消息null given,因为我有[{1}}作为参数1。

有谁知道我做错了什么?

1 个答案:

答案 0 :(得分:-1)

您正在尝试捕获查询错误,但是在显示$ _POST var错误的位置使用它。请参阅改进的代码:

  <?php

  if (!empty($_POST['var1'])&&!empty($_POST['var2'])
    &&!empty($_POST['var3'])&&isset($_POST['var4'], 
    $_POST['var5'], $_POST['var6'])) {

    require_once 'connect.inc.php'; 

    $query = "INSERT INTO tablename (var1, var2, var3, var4, var5, var6)
    VALUES (?,?,?,?,?,?)";

    $stmt = mysqli_prepare($link, $query);

    $var1 = $_POST['var1'];
    $var2 = $_POST['var2'];
    $var3 = $_POST['var3'];
    $var4 = $_POST['var4'];
    $var5 = $_POST['var5'];
    $var6 = $_POST['var6'];

    mysqli_stmt_bind_param($stmt, "ssssss", $var1, $var2, $var3, $var4, $var5, $var6);
    mysqli_stmt_execute($stmt);

     if (mysqli_stmt_affected_rows($stmt)==1) {
          echo 'Thank you for your submission.';
        } else {
          mysqli_stmt_close($stmt);
          mysqli_close($link);  

          // do something with your statement error
          echo mysqli_stmt_error($stmt);
        }

} else {
  echo 'We were unable to process your information. Please ensure all required fields were filled out.';
} 
?>