How show foreach if/else in php

SQL Table is shown below.

---------------------------------
|     id    |     product_id    |
---------------------------------
|     1     |       700         |
|     2     |     200,700,800   |
|     3     |        0          |
|     4     |    330,840,842    |
---------------------------------

And that code is written in PHP and For now I have the following code:

$query = "SELECT * FROM products"; $result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result)) {    
  if($row['product_id']) {
    $data = preg_split('/,/', $row['product_id']);
     if(is_array($data)) {
       foreach($data as $key => $value) {
           if($value == 605) {
               echo 'Yes.';
           }
       }
     } 
  }
}

The value of 605 is not displayed in the output. Is that value in the database table or not?

If there is a database table Show its output:

Yes.

And if it doesn't exist Show its output:

No.

How can this be done in PHP and show its output?

2 answers

  • answered 2019-12-09 09:37 Divyesh Jani

    make one variable initialize with "No" then at the end of code just echo that value:

    $result = "No";
    //Your code
    $query = "SELECT * FROM products";
    $result = mysqli_query($db, $query);
    while ($row = mysqli_fetch_array($result)) {
        if ($row['product_id']) {
            $data = preg_split('/,/', $row['product_id']);
            if (is_array($data)) {
                foreach($data as $key => $value) {
                    if ($value == 605) {
                        $result = "Yes"
                    }
                }
            }
        }
    }
    echo $result
    

  • answered 2019-12-09 09:37 jared

    $match = false;
    //Your code
    $query = "SELECT * FROM products";
    $result = mysqli_query($db, $query);
    while ($row = mysqli_fetch_array($result)) {
        if ($row['product_id']) {
            $data = preg_split('/,/', $row['product_id']);
            if (is_array($data)) {
                foreach($data as $key => $value) {
                    if ($value == 605) {
                        $match = true
                    }
                }
            }
        }
    }
    $match ? echo "Yes" : echo "No";