1

I'm using while loop to fetch data from the database I want to display like nothing found the result is null or empty. I've tried using if/else with like: if (empty($jobs)) echo 'nothing found'; that doesn't work. if(!mysqli_fetch_assoc($jobs)) works but if don't show the jobs if available.

Loop

  <?php while ($job = mysqli_fetch_assoc($jobs)) { ?>
  <tr class="custom-table-body-titles">
    <td><?php echo h($job['updated_at']); ?></td>
    <td>
      <a href="#" class="text-dark"><?php echo h($job['title']); ?></a>
    </td>                
    <td>0/<?php echo h($job['required_freelancers']); ?></td>
    <td><?php echo h($job['delivery_time']); ?> Days</td>
    <td>$<?php echo h($job['budget']); ?></td>
    <td>
      <a href="job_details.html" class="btn btn-sm btn-primary">Apply</a>
    </td>
  </tr>
  <?php } ?>
Dharman
  • 30,962
  • 25
  • 85
  • 135

3 Answers3

1

You have to do a validation to check if any results were found before even starting the loop. Assuming $jobs is an instance of mysqli_result returned by mysqli_query().

if (mysqli_num_rows($jobs) > 0)
{
    // your while loop
}
else
{
    echo "no jobs found";
}
Bär Ger
  • 62
  • 5
1

You should keep PHP and HTML separate as much as you can.

You can fetch all results into an array before and then foreach on that array.

$jobs = $jobs->fetch_all(MYSQLI_ASSOC);

if($jobs) {
    foreach ($jobs as $job) {
    }
} else { 
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
1

A good question which is sadly most of time is answered incorrectly.

It's a very bad practice to mix the database-related code and HTML code. There should never be a while loop like this.

Instead, the data should be fetched into array,

$jobs = [];
while ($row = mysqli_fetch_assoc($result)) {
    $jobs[] = $row;
}

which is then used to output the data. And once you have this array, you can use it to tell whether the query returned any data or not:

<?php if ($jobs) { ?>
  <?php foreach ($jobs as $job) { ?>
  <tr class="custom-table-body-titles">
    <td><?php echo h($job['updated_at']); ?></td>
    <td>
      <a href="#" class="text-dark"><?php echo h($job['title']); ?></a>
    </td>                
    <td>0/<?php echo h($job['required_freelancers']); ?></td>
    <td><?php echo h($job['delivery_time']); ?> Days</td>
    <td>$<?php echo h($job['budget']); ?></td>
    <td>
      <a href="job_details.html" class="btn btn-sm btn-primary">Apply</a>
    </td>
  </tr>
  <?php } ?>
<?php } else {?>
    no data
<?php } ?>
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345