Jump to content

Trouble with mysqli


Sepio

Recommended Posts

Hi, I'm tearing my hair out trying to get this to work, let alone understand why. Could someone please explain what's failing here? Here's the offending section of code:

 

<?php
if ($ug_stmt = $mysqli->prepare("SELECT group FROM users_groups WHERE user = ? ORDER BY group")) {
    $ug_stmt->bind_param('s', $username);
    $ug_stmt->execute();
    if ($ug_stmt->num_rows > 0) {
        if ($ug_result = $ug_stmt->store_result()) {
            while ($ug_row = $ug_result->fetch_row()) {
                echo $ug_row[0] . '<br>';
            }
            $ug_result->free();
        }
    } else { echo 'No results found'; }
}
?>

 

(This is the entirity of get_usergroups.php file that's required by other scripts, so line numbers in error messages below are accurate.)

 

This causes 'No results found' to be echoed, but when the query is tested in phpMyAdmin it returns three rows as it should. $username is defined far in advance of this section, and if echoed within the outermost conditional, is indeed the username of the user currently logged in, so that's not the problem.

 

Then I suspect I can't find out num_rows until I've created a results object, which makes sense in my head, but when I comment out that conditional I get the following error:

 

Fatal error: Call to a member function fetch_row() on a non-object in C:\xampp\htdocs\users\includes\get_usergroups.php on line 9

 

So apparently $ug_result isn't an object, which I'm confused about because surely I've just created it… The PHP manual says store_result() returns either a result object or FALSE. Maybe it's returning FALSE because of whatever it is that's preventing rows being returned.

 

So I check it with printf but that claims the value of $ug_result is "1", which doesn't stike me as being either a result set or FALSE. gettype confirms it's a Boolean, but the manual doesn't say anything about this being possible.

 

I've been using PHP for about 6 years, but I've only just started learning OOP in the last couple of months.

 

Many thanks,

Sepio

Link to comment
https://forums.phpfreaks.com/topic/205336-trouble-with-mysqli/
Share on other sites

->store_result() will always return a BOOL (true or false.)

 

All ->store_result() does is buffer all the rows. You must use $ug_stmt->fetch() to fetch those rows or use $ug_stmt->result_metadata(); to return a result object so that you can use the result object to access the result set.

Link to comment
https://forums.phpfreaks.com/topic/205336-trouble-with-mysqli/#findComment-1074675
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.