Can I get results from mysqli_stmt_bind_result without looping through it?

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?

Answers


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

Need Your Help

Managed Reg-Free COM Server Won't Activate

c# c++ com vb6 regfreecom

I started with a very sophisticated system of clients and servers with COM references and other things, and I've cut down and down until I realized I can't even get Microsoft sample code to work for