Why would print_r ($row); only be returning a number 1?
Question
I am trying to learn PHP5 and am having a couple of problems with it. I am working with prepared statements and am trying to run the following code:
<?php
require_once 'includes/config.php';
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database.');
$query = "SELECT * FROM user_table";
if($stmt = $conn->prepare($query)) {
$stmt->execute();
while ($row = $stmt->fetch()) {
print_r ($row);
}
}
?>
I have 2 rows it should return each containing an id, login_name, login_password and a login_level.
When the statement runs it only prints the following:
11
Any help would be greatly appreciated.
Solution
The fetch() method returns TRUE
, FALSE
, or NULL
depending on whether it succeeded in fetching the data. It doesn't return the data in an array. Instead it places the results in variables bound by the bind_result() method.
OTHER TIPS
It returns 1 because 1 is TRUE in PHP.
What you should do is bind a variable with the [bind_result][1]
method and then do:
while ($stmt->fetch()) {
printf ("%s\n", $variable);
}
A great example is on the bind result documentation page.
To be able to get that this way you first need to bind the result variables like this:
$stmt->execute();
// bind the result variables in order
$stmt->bind_result($id, $login_name, $login_password, $login_level);
// then get results
while ($stmt->fetch()) {
var_dump($id, $login_name, $login_password, $login_level);
}