dpj83664 2014-01-27 11:47
浏览 61
已采纳

mysqli :: prepare()vs mysqli_stmt :: prepare()

I was using the following code to make a query with prepared statements: I used mysqli::prepare(), NOT mysqli_stmt::prepare(), so $res does not have to be initialized. It is returned by mysqli::prepared. php.net link

$sql2 = "INSERT INTO best_scores(`user_id`, `test_id`, `score`) VALUES(?, ?, ?)";
if($res = $db->prepare($sql2) == FALSE) echo $db->error . "
";
$res->bind_param("sii", $user_id, $_GET['test'], $max);
$res->execute();
$res->free_result();

When that code was reached, the following error appeared:

Call to a member function bind_param() on a non-object

I looked for answers but all the questions had mistakes in the SQL query string or they didn't free the previous results. None of them helped me, so I tried to change something. I changed my code into this:

$sql2 = "INSERT INTO best_scores(`user_id`, `test_id`, `score`) VALUES(?, ?, ?)";
$res = $db->stmt_init();
if($res->prepare($sql2) == FALSE) echo $db->error . "
";
$res->bind_param("sii", $user_id, $_GET['test'], $max);
$res->execute();
$res->free_result();

Now it is working. But why is it different? What was the problem with the first attempt?

Edit: My $db object is defined like this:

$db = new mysqli("localhost", "user", "pass", "database");
if($db->connect_errno > 0) {
    die('Unable to connect to database [' . $db->connect_error . ']');
}
  • 写回答

3条回答 默认 最新

  • douhang8991 2014-01-27 12:23
    关注

    As we discuss it in the comments, it might be a wrong assignation in the if() block.

    What do I tested. If block, like yours:

    $x = (object)array('a'=>'b');
    
    if ($a = $x == false) {
        echo 'a';
    }
    
    var_dump($a);
    

    Output:

    boolean false

    Then I have put parentheses around the assignation:

    $x = (object)array('a'=>'b');
    
    
    if (($a = $x) == false) {
        echo 'a';
    }
    
    var_dump($a);
    

    Output:

    object(stdClass)[1] public 'a' => string 'b' (length=1)

    so you would need to put parentheses around the assignation for $res

    if(($res = $db->prepare($sql2)) == FALSE) 
    

    Because your way, you wrongly reassign $res to FALSE and the object has been lost

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable