user3724476 user3724476 - 1 year ago 57
MySQL Question

While and if statement in php with mysql

I have been stuck with this problem for awhile now. I'm sure the answer is on easily find able on Google but I have been unable to find the words to search so my last resort is here. Thanks in advanced!

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". What I am trying to accomplish is if ANY of the entries have status = "Opened", $test will return "1".

Once again thanks in advance for all your help!

Answer Source

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;

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

  // do your stuff;