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?