1

I have this php code:

if(mysqli_num_rows($query) > 0) {
    while($row = mysqli_fetch_array($query)) {
        if ($row['status'] == "Opened") {
            $test = "1";
        } else {
            $test = "0";
        }
    }
}
echo $test;

The problem occurs when there are multiple entries in the database and one of those entries does not have status = "Opened" therefore $test returns "0". I am trying to accomplish that if ANY of the entries have status = "Opened", $test will return "1".

2
  • You should not be doing this with a loop in php. You should be doing this with a single query in the database. Commented Nov 5, 2016 at 19:35
  • That will depend on what the query is for this, that you didn't post. Commented Nov 5, 2016 at 19:55

2 Answers 2

2

It might be better to directly select the data you need from the database instead of filtering it out with PHP.

SELECT id, message, etc FROM tickets WHERE status = 'Opened'
// if it fetches data, you have open tickets and have directly access to the data of the open tickets.

SELECT count(*) AS total FROM tickets WHERE status = 'Opened'
// the result of this is a number of the total amount of opened tickets, perhaps better for this specific use.

But on the subject on how to fix your loop you can do the following:

$open = false;

while($row = mysqli_fetch_array($query)) {
    if ($row['status'] == "Opened") {
        $open = true;
        break;
    } 
}

As this will quit the while loop, setting $open for futher use:

if($open){
  // do your stuff;
}
Sign up to request clarification or add additional context in comments.

Comments

2

All you need to do is the following:

$query = "SELECT `status` FROM `table` WHERE `status` = 'Opened'";
$result = mysqli_query($conn, $query);
$test = (mysqli_num_rows($result) > 0) ? 1 : 0;

No need to fetch, it will be faster too.

2 Comments

Upon testing it only returns the value "0".
Double check your table because this code is correct

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.