dongpai1942 2015-11-27 20:41
浏览 123
已采纳

我可以从mysqli_stmt_bind_result获得结果而不通过它循环吗?

Using http://php.net/manual/en/mysqli-stmt.bind-result.php as a reference, I created:

$conn = new mysqli($host, $user, $password, $database) or die("Error " . mysqli_error($link));

$userID = json_decode(file_get_contents('php://input'), true)["userID"];

$sql = "SELECT name
          FROM users
         WHERE id = ?";

$stmt = mysqli_prepare($conn, $sql);

if ($stmt) {
  mysqli_stmt_bind_param($stmt, "i", $userID);

  if (mysqli_stmt_execute($stmt)) {
    mysqli_stmt_store_result($stmt);

    if (mysqli_stmt_num_rows($stmt) > 0) {
      mysqli_stmt_bind_result($stmt, $name);

      while (mysqli_stmt_fetch($stmt)) {
        if ($name != "") {
          echo '{"name": ' . $name . '}';
        } else {
          echo '{"name": "Anonymous" }';
        }
      }
    }
  }
}

The way this is now, it works in getting the user's name.

However, I'm reluctant to use a while loop when I know my query is only returning one row, so I looked for ways to get the value without using a loop but couldn't find any.

I tried removing the while loop just to see what would happen, and it failed to get the user's name. Is there a way I can get the result of my query using mysqli_stmt_bind_result without using a loop? If not, is there something else I can use to do what I want?

  • 写回答

1条回答 默认 最新

  • duanfang7757 2015-11-27 21:13
    关注

    Yes, when you're only expecting one row, and know that it will only return that one, to be returned you don't need to loop over anything - it would be redundant.

    You can remove the while-loop, but you'd still need the argument, mysqli_stmt_fetch($stmt) to actually fetch the results.

    if ($stmt = mysqli_prepare($mysqli, $sql)) {
        mysqli_stmt_bind_param($stmt, "i", $userID);
    
        if (mysqli_stmt_execute($stmt)) {
            mysqli_stmt_store_result($stmt);
    
            if (mysqli_stmt_num_rows($stmt) > 0) {
                mysqli_stmt_bind_result($stmt, $name);
    
                mysqli_stmt_fetch($stmt);
                if (!empty($name)) {
                    echo '{"name": ' . $name . '}';
                } else {
                    echo '{"name": "Anonymous" }';
                }
            } else {
                // No results!
                echo "No results";
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 SPSS分类模型实训题步骤
  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红
  • ¥15 想问问富文本拿到的html怎么转成docx的
  • ¥15 我看了您的文章,遇到了个问题。