Patricio Carvajal H. Patricio Carvajal H. - 7 months ago 24
SQL Question

MySQLi OOP Bind Parameters Error

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 />';
}

Answer

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 />';
}
Comments