Search code examples
phpmysqlselectmysql-num-rows

mysqli num_rows does not return correct number of rows - all values checked


I'm trying to show icon.envelop.2.gif if there are any messages with message_status = 2. However for some obscure reason this query returns 0. What have I missed here?

The $_SESSION['user_id'] is valid, and so is $access_level. I have checked my table and I have 1 input with the correct message_receive number and I have also tried using message_to_stab = 5 which is the correct number.

This is the information in my database:

  • message_id = 1
  • message_receive = 697
  • message_status = 2
  • message_to_stab = 5 or message_to_stab = NULL

This is my information in session and access_level:

  • access_level = 5
  • $_SESSION['user_id'] = 697

This is my code:

$sql = "SELECT message_id FROM private_messages WHERE message_status = 2 AND (message_receive = ? OR message_to_stab = ?)";
$stmt = $mysqli->prepare($sql) or die ("Database error: <br>" . $sql . "<br><b>Error message:</b> " . $mysqli->error);
$stmt->bind_param("ii", $_SESSION['user_id'], $access_level);
$stmt->execute() or die("Something went wrong");

if($stmt->num_rows != 0){
    $html .= 'icon.envelope.2.gif';
}
else{
    $html .= 'icon.envelope.gif';
}

$stmt->free_result();
$stmt->close();

Here is the problem, no errors, I want BOTH mailing symbols to be like the one under status.

Image showing messaging error


Solution

  • I managed to use $stmt->fetch() to solve the problem. I had to change the query to LIMIT 1 in order to prevent errors when more than 1 unread message available.

    if($stmt->fetch()){
        $html .= 'icon.envelope.2.gif';
    }
    else{
        $html .= 'icon.envelope.gif';
    }
    

    PS: Better answers are more than welcome. I still dont know why rowCount() or num_rows didn't work.