views:

365

answers:

3

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.

+5  A: 

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.

yjerem
+1  A: 

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.

Ólafur Waage
+1  A: 

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);
}
fromvega