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

时间:2015-11-27 20:41:34

标签: php mysqli

使用http://php.net/manual/en/mysqli-stmt.bind-result.php作为参考,我创建了:

$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" }';
        }
      }
    }
  }
}

现在这样,它可以获取用户的名字。

但是,当我知道我的查询只返回一行时,我不愿意使用while循环,所以我想方法在不使用循环但没有找到任何循环的情况下获取值。

我尝试删除while循环只是为了看看会发生什么,并且它无法获得用户的名字。有没有办法在不使用循环的情况下使用mysqli_stmt_bind_result获取查询结果?如果没有,还有什么我可以用来做我想做的事吗?

1 个答案:

答案 0 :(得分:2)

是的,当你只想要一行,并且知道它只返回那一行时,要返回,你不需要循环任何东西 - 这将是多余的。

您可以删除while - 循环,但您仍然需要参数mysqli_stmt_fetch($stmt)来实际获取结果。

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";
        }
    }
}