0
    // Populate headers
    $fields = $result->fetch_fields();
    foreach ($fields as $field)
        printf("<th>%s</th>", $field->name);

    printf("</tr>");

    // Write to table
    while ($myvar = $result->fetch_row()) {

        $date = $myvar[0];
        $room_ID = $myvar[1];
        $description = $myvar[2];
        $firstname = $myvar[3];
        $lastname = $myvar[4];
        $message = $myvar[5];
        $period = $myvar[6];

        printf("<tr>");
        printf("<td>%s</td><td>%s</td>", $date, $room_ID);
        printf("<td>%s</td><td>%s</td>", $description, $firstname);
        printf("<td>%s</td><td>%s</td><td>%s</td>", $lastname, $message, $period);
        printf("</tr>");

  }

I'm trying to echo "No results to display" if my MySQLi result returns empty. The problem is the headers are returned as part of the array, how can I achieve this?

1

4 Answers 4

1

You need to check with number of rows. if it return zero it means table contain no rows. try below code.

// Populate headers
    $fields = $result->fetch_fields();
    foreach ($fields as $field)
        printf("<th>%s</th>", $field->name);

    printf("</tr>");

    // Write to table
    if($result->num_rows== 0){
     echo "No Result to display";
    }else{
    while ($myvar = $result->fetch_row()) {

        $date = $myvar[0];
        $room_ID = $myvar[1];
        $description = $myvar[2];
        $firstname = $myvar[3];
        $lastname = $myvar[4];
        $message = $myvar[5];
        $period = $myvar[6];

        printf("<tr>");
        printf("<td>%s</td><td>%s</td>", $date, $room_ID);
        printf("<td>%s</td><td>%s</td>", $description, $firstname);
        printf("<td>%s</td><td>%s</td><td>%s</td>", $lastname, $message, $period);
        printf("</tr>");

  }

}

Sign up to request clarification or add additional context in comments.

Comments

1

Simple use num_rows

  if($result->num_rows== 0){
 echo "no results to display"
  }
else{
  while ($myvar = $result->fetch_row()) {
  //Your Code here
 }

Comments

1

You can use num_rows to get the total value of records.

$row_count = $result->num_rows;
if($row_count>0)
{ 
    echo "Data Available";
}
else
{
    echo "No Data Available";
}

Comments

1

You can use num_rows to get the total value of records retrieved from the query.

$row_cnt = $result->num_rows;
if($row_cnt>0){ echo "Have data";}else{echo "No data";}

Comments

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.