0
<?php

$output = "";
if(isset($_POST["query"]))
{
 $search = $_POST["query"];
 $sql = ("
  SELECT * FROM `products` 
  WHERE productName LIKE :sText
  OR productLine LIKE :sText
  OR productVendor LIKE :sText
  OR MSRP LIKE :sText
 ");
 $stmt=$db->prepare($sql);
}
elseif
{
 $sql = "SELECT * FROM products";
 $stmt=$db->prepare($sql);
}
$stmt->execute(array(':sText'=>'%'. $search .'%'));
foreach($stmt as $row)
{
 $output = " 
          <div class='product_wrapper'>
        <form method='post' action=''>
        <table style='width:170px;height:143px;''>
        <tr>
        <td><input type='hidden' name='productCode' value=". $row['productCode']." />
        <div class='name'>".$row['productName']."</div>
        <div class='price'>RM". $row['MSRP']."</div></td>
        </tr>
        <table style='width:170px;height:60px'>
        <tr>
        <td><button type='submit' class='buy' style='margin: : 25px;'>Buy Now</button></td>
        </tr>
        </table>
        </table>
        </form>
          </div>
 ";
 echo $output;
}

else
{
 echo 'Data Not Found';
}

?>

I have problem on what is the condition needed for elseif condition in order to add else echo data not found in the end. I have to find out what is the elseif condition I can add. Appreciate for your help guys.

Iwo Kucharski
  • 3,735
  • 3
  • 50
  • 66
Mr. S
  • 25
  • 3

2 Answers2

0

You cannot use else with foreach, therefore you need to check if you have any results before using the foreach statement.

if($stmt->rowCount() > 0) {
    foreach($stmt as $row)
    {
        $output = echo" 
          <div class='product_wrapper'>
        <form method='post' action=''>
        <table style='width:170px;height:143px;''>
        <tr>
        <td><input type='hidden' name='productCode' value=". $row['productCode']." />
        <div class='name'>".$row['productName']."</div>
        <div class='price'>RM". $row['MSRP']."</div></td>
        </tr>
        <table style='width:170px;height:60px'>
        <tr>
        <td><button type='submit' class='buy' style='margin: : 25px;'>Buy Now</button></td>
        </tr>
        </table>
        </table>
        </form>
        </div>";

     $output;
    }
} else {
    echo 'Data Not Found';
}
Kristen
  • 16
  • 3
0

You can use rowCount to get the number of affected rows

Try this

 if($stmt->rowCount() > 0) {
   //Loop throught the rows
 }else{
    echo "No matching records found.";
 }

Check this for more details PDOStatement::rowCount

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20