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 Answers 2

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 />';
}
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

->get_result() another good alternative if this method is available in your env @PatricioCarvajalH
@PatricioCarvajalH.Ah yes, thanks for reminding me that this is not always available, added a note to that effect
@RiggsFolly thank you. Found those interesting links: stackoverflow.com/questions/18753262/… stackoverflow.com/questions/8321096/… When to use bind_result vs get_result in mysql --> arian.io/when-to-use-bind_result-vs-get_result-in-mysql

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.