MySQLi while loop

I appear to have done something wrong here. Even though SQL results more than 1 row, the while loop only cycles the once and stops. Any ideas why?

$stmt = mysqli_prepare($sql_connect, "SELECT x from messages");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $x);
mysqli_stmt_store_result($stmt);

if ((mysqli_stmt_num_rows($stmt) == 0)) {
    echo "No messages founds";
    die();
}
    
while (mysqli_stmt_fetch($stmt)) {
echo "Do something";
}

The note I read suggests that you need to call bind_result() after you call store_result(), not in the order you have it. I haven’t used mysqli so I can’t say for sure.

It’s been a long time since I’ve used MySQLi, but I don’t think you need to use this when you’re binding.

Just out of curiosity, is there a reason that you’re not using PDO? It’s definitely the preferred option these days

Because it’s object based :frowning:

Don’t be afraid :slight_smile:

1 Like

Too late, already have brown stains :frowning:

Interested in letting me show you the way? Not a “do it this way” but a “how to do it and why”?

Maybe your next blog for Sitepoint? :smiley:

Scott

“Don’t be afraid of PDO” by Antnee :slight_smile:

2 Likes

I really don’t understand object based php code and I’ve rather not start learning it now 90% the way through my project :stuck_out_tongue:

Also I figured out why my loop wasn’t working. I was looping through the results of $stmt, however created a new $stmt within the loop. School boy error I guess.

I don’t expect you to rewrite your project, but I would like to help you learn something new by the time you’ve finished the last 10%, and maybe you’ll consider it for the next project? I’m going to see if I have the time to write something up later to help people understand and to migrate from either MySQL or MySQLi to PDO. You’re welcome to read it or ignore it, but I think that if people are scared of it then the community has done a bad job of helping. I do understand the reluctance though; I was the same. Everyone is different though.

Back on topic, I’m glad that you worked out what’s wrong :slight_smile: Presumably your example code would’ve worked OK then, and it’s the code that was removed for brevity that caused the issue. Maybe an IDE that points out that you’re reassigning a variable (which is usually a bad sign) would help in future?

I had a little go at writing an article about the basic differences between MySQL, MySQLi and PDO. I will write up actual migration tips when I get the chance, most likely next week now. Let me know if you think it helps though

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.