1

I am starting with MySQLi, I started with a simple select and it works:

$sql = "SELECT nombres, apellidos FROM users WHERE user = 'juan'";
$result = $con->query($sql);
while($row = $result->fetch_object()){
    print $row->nombres . '<br />';
    print $row->apellidos . '<br />';
}

But when I'm trying out using prepared statements have no results displayed... what am I doing wrong?

$user = 'juan';
$sql = "SELECT nombres, apellidos FROM users WHERE user = ?";
$result = $con->prepare($sql);
$result->bind_param('s', $user);
$result->execute();

while($row = $result->fetch_object()){
    print $row->nombres . '<br />';
    print $row->apellidos . '<br />';
}

2 Answers2

1

Using fetch in prepared statements is a little bit different. There's another fethcing API for mysqli prepared statements and you'll need to use ->bind_result() and stmt_fetch() for it to work.

$result->bind_param('s', $user);
$result->execute();
$result->bind_result($nombres, $apellidos);

while($result->fetch()){
    print $nombres . '<br />';
    print $apellidos . '<br />';
}
Kevin
  • 41,694
  • 12
  • 53
  • 70
1

An execute will return a mysqli_statement object. If you want to process the results of the query like they were a mysqli_result object you have to run a $stmt->get_result() to convert it to a mysqli_result object, then you can process as a mysqli_result object with a while loop as you were doing

$user = 'juan';
$sql = "SELECT nombres, apellidos FROM users WHERE user = ?";
$stmt= $con->prepare($sql);
$stmt->bind_param('s', $user);
$stmt->execute();

$result = $stmt->get_result();

while($row = $result->fetch_object()){
    print $row->nombres . '<br />';
    print $row->apellidos . '<br />';
}

Unfortunately this function/method is only available if you have the Native Driver mysqlnd installed.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • `->get_result()` another good alternative if this method is available in your env @PatricioCarvajalH – Kevin May 05 '16 at 23:02
  • @PatricioCarvajalH.Ah yes, thanks for reminding me that this is not always available, added a note to that effect – RiggsFolly May 06 '16 at 08:04
  • 1
    @RiggsFolly thank you. Found those interesting links: http://stackoverflow.com/questions/18753262/example-of-how-to-use-bind-result-vs-get-result http://stackoverflow.com/questions/8321096/call-to-undefined-method-mysqli-stmtget-result When to use bind_result vs get_result in mysql --> https://arian.io/when-to-use-bind_result-vs-get_result-in-mysql/ – Patricio Carvajal H. May 06 '16 at 19:48