I have the following code which performs a simple query that will only return one row every time.
if ($statement = mysqli->prepare('SELECT ID, FirstName, LastName, Email FROM People WHERE Email = ?')) {
$statement->bind_param('s', $_POST['email-address']);
$statement->execute();
$statement->store_result();
if ($statement->num_rows > 0) {
$statement->bind_result($ID, $FirstName, $LastName, $Email);
}
}
How can I display the information now without using a while loop like every example I’ve seen online? Simply using $FirstName, for example, does nothing. I’m open to other methods too. execute(), store_result(), bind_results(), etc…, etc… are too many steps if you ask me, but maybe that’s the only option with prepared statements.
Simply using $FirstName, for example, does nothing.
you need to call mysqli_stmt->fetch() before the bound parameters are populated.
from the Manual:
When mysqli_stmt_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var1, …
(rule of thumb for prepared statements: you always need the call triad prepare-execute-fetch (although fetch() may in some cases be called implicitly) for a SELECT (UPDATE, INSERT, etc. obviously need no fetch))
if ($statement = mysqli->prepare('SELECT ID, FirstName, LastName, Email FROM People WHERE Email = ?')) {
$statement->bind_param('s', $_POST['email-address']);
$statement->execute();
$statement->store_result();
if ($statement->num_rows > 0) {
$statement->bind_result($ID, $FirstName, $LastName, $Email);
$statement->fetch();
echo $FirstName; // Outputs the first name
}
}