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

我可以从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";
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 matlab解优化问题代码
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline