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 请提供一个符合要求的网页链接。
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码