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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改