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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化