douyi4912 2013-05-23 08:41
浏览 37
已采纳

连续的MySQLi编写的语句不起作用

I want to make successive calls to MySQL stored routines (using prepared statements) from the same PHP file, like this:

$conn = getconn();
$stmt = $conn->prepare("CALL GetUserLoginData(?);");
$stmt->bind_param("s", $username);
$stmt->execute();

// Process data here... until next stored routine call

$conn = getconn();
// var_dump($conn);
$stmt2 = $conn->prepare("CALL SetUserLoginTime(?);");
$stmt2->bind_param("i", $userid);
$stmt2->execute();

where getconn() returns a database connection with new mysqli().

This code works on a web server running PHP 5.3.8-1/MySQL 5.1.54, but not on a server with PHP 5.3.10/5.5.29.

If I uncomment var_dump($conn) I get ["error"]=> string(52) "Commands out of sync; you can't run this command now".

I can't figure out why this is happening on just one server.

  • 写回答

3条回答 默认 最新

  • dongwenghe2416 2013-05-23 08:44
    关注
    $conn = getconn();
    $stmt = $conn->prepare("CALL GetUserLoginData(?);");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    
    // Process data here... until next stored routine call
    
    $conn = getconn();
    // var_dump($conn);
    $stmt2 = $conn->prepare("CALL SetUserLoginTime(?);");
    $stmt2->bind_param("i", $userid);
    $stmt2->execute();
    

    Because prepared statements use an unbuffered query type. You have two options:

    1) Close your query after executions

    $conn = getconn();
    $stmt = $conn->prepare("CALL GetUserLoginData(?);");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->close(); // Frees the buffer
    

    2) Use free_results: http://php.net/manual/en/mysqli-result.free.php

    Scenario Not Within Your Question:

    Sometimes Closing the query or freeing the results is not an option. For example a while loop... In A Situation like this, you should use:

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

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作