猿问

如果实时搜索框输入与数据库不匹配,如何显示未找到数据?

<?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';

}


?>

为了添加其他未找到的回显数据,我对elseif条件所需的条件有疑问。我必须找出可以添加的elseif条件。感谢您的帮助。


开满天机
浏览 134回答 2
2回答

POPMUISE

您不能将else与foreach一起使用,因此需要在使用foreach语句之前检查是否有任何结果。if($stmt->rowCount() > 0) {&nbsp; &nbsp; foreach($stmt as $row)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $output = echo"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class='product_wrapper'>&nbsp; &nbsp; &nbsp; &nbsp; <form method='post' action=''>&nbsp; &nbsp; &nbsp; &nbsp; <table style='width:170px;height:143px;''>&nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <td><input type='hidden' name='productCode' value=". $row['productCode']." />&nbsp; &nbsp; &nbsp; &nbsp; <div class='name'>".$row['productName']."</div>&nbsp; &nbsp; &nbsp; &nbsp; <div class='price'>RM". $row['MSRP']."</div></td>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; &nbsp; &nbsp; <table style='width:170px;height:60px'>&nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <td><button type='submit' class='buy' style='margin: : 25px;'>Buy Now</button></td>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; &nbsp; &nbsp; </table>&nbsp; &nbsp; &nbsp; &nbsp; </table>&nbsp; &nbsp; &nbsp; &nbsp; </form>&nbsp; &nbsp; &nbsp; &nbsp; </div>";&nbsp; &nbsp; &nbsp;$output;&nbsp; &nbsp; }} else {&nbsp; &nbsp; echo 'Data Not Found';}

梵蒂冈之花

您可以rowCount用来获取受影响的行数试试这个&nbsp;if($stmt->rowCount() > 0) {&nbsp; &nbsp;//Loop throught the rows&nbsp;}else{&nbsp; &nbsp; echo "No matching records found.";&nbsp;}检查更多信息PDOStatement :: rowCount
随时随地看视频慕课网APP
我要回答