0

I have a table in my database and It has 4 columns, In these columns, a column, named "Post_status". This column has two types of values one is "Published" and the other one is "Draft". I wanna that If all values are equal to "Draft" then echo 'No Post found' and If even one value is equal to "Published" then echo 'Post Found'. I have tried lots of time with if statement but I couldn't... Because mysqli_query gives me all the values together like this "DraftPublishedPublishedDraft..."

How can I check each value of the column?

<?php
$query = "SELECT * FROM posts ";
$getAll_postsStatus = mysqli_query($connection, $query);

while ($row = mysqli_fetch_assoc($getAll_postsStatus)) {
   $post_status = $row['post_status'];                   
}    

if ($post_status != 'Published' ) {
    echo "<h2>No Post found!</h2>";
} else {
  echo "<h2>Found Posts!<h2>";
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Praveen Kumar
  • 49
  • 1
  • 6

2 Answers2

0

You are overwriting $post_status every time you get a new row so the result is always going to be whatever the last row in the result set is. Instead, use SQL to get your answer with a single query.

$pub_status = mysqli_query($connection,"SELECT COUNT(*) as pub_count
              FROM posts 
              WHERE post_status = 'Published'");
$row = mysqli_fetch_assoc($pub_status);
if ($row['pub_count'] == 0) {
    echo "<h2>No Post found!</h2>";
} else {
    echo "<h2>Found Posts!<h2>";
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Dave
  • 5,108
  • 16
  • 30
  • 40
-2

if you want to show message after every iteration then put those if checks inside that while loop. and if want to post found even one published is found then you can do something like this.

 $query = "SELECT * FROM posts where post_status='Published'";
 $getpublished = mysqli_query($connection, $query);
 $rowcount=mysqli_num_rows($getpublished);


 if($rowcount>0){
   echo "<h2>Found Posts!<h2>";
 }else{
   echo "<h2>No Posts Found!<h2>";
 }

// mysqli_num_rows will give you a number of rows with published post_status

check this out: https://www.w3schools.com/pHp/func_mysqli_num_rows.asp