You should, at the very least, be using prepared statements in your queries if you're passing them user-supplied data.
- use prepared statements
?
and bind_param
- use
bind_result
to bind the column to a variable. This variable is now bound by reference which means it will be updated on every iteration of the loop.
- it is important to realize that you want to access the
$id
variable inside the loop as you're iterating over the dataset. If you use it outside/below the loop you are only working with the final row of data because it is being overwritten on every iteration.
- turn on error reporting
Finally, I left your loop in place but usually, you'd only have a single user for a given username so you could use mysqli_fetch_assoc
- Single Result from Database by using mySQLi
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$username = $_POST['username'];
$query = "SELECT id FROM wp_users WHERE user_login = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch()) {
echo "ID: $id\n";
}
$stmt->close();