jimmy jimmy - 6 months ago 23
SQL Question

mysqli_fetch_assoc() not returning anything

This is not the first time I have used

mysqli_fetch_assoc()
to get a specific column of a row. For some reason I can not figure out why it is not working this time around. Heres my code:

$sql = "SELECT * FROM database.table WHERE PushNumber > 0";
$result = $conn->query($sql);

if($result->num_rows > 0) {
while($row = mysqli_fetch_array($result)) {
// This will loop through each row, now use your loop here
$row = mysqli_fetch_assoc($result);
$pushNumber = $row['PushNumber'];
$followingIDs = $row['FollowingIDs'];
$usernameID = $row['Username'];
error_log("'$pushNumber", 0);
error_log("'$usernameID", 0);
}
}


There is one row in my table where
PushNumber
is greater than
0
and
$pushNumber
(type:
int
) and
$usernameID
(type:
string
) are printed in the error log and both are printed as:
''
AND I DON'T KNOW WHY! There are no spelling errors and I know for a fact in that row
PushNumber
is equal to
1
and
Username
is equal to
@yo
. Any suggestions would be appreciated please help. Thank you!

Answer

You appear to assign to completely different sets of values into your $row variable.

$row = mysqli_fetch_array($result) transfers the entire array into $row, but then in your loop you use $row = mysqli_fetch_assoc($result) to transfer a single record into $row, which is most likely throwing your loop off.

Try this:

if($result->num_rows > 0) 
{
    while($row = mysqli_fetch_assoc($result)) 
    {
        // This will loop through each row, now capture each row's data here
        $pushNumber = $row['PushNumber'];
        $followingIDs = $row['FollowingIDs'];
        $usernameID = $row['Username'];
        error_log($pushNumber, 0);
        error_log($usernameID, 0);
    }
}
Comments