php mysqli搜索如果找到显示否则说找不到

时间:2014-10-27 22:52:15

标签: php mysql mysqli

    <?php
    $con= new mysqli("localhost","root","","cars");
    $name = $_POST['Search'];

    if (mysqli_connect_error())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

$result = mysqli_query($con, "SELECT * FROM cars
     WHERE vin LIKE '%{$name}%' OR license_plate LIKE '%{$name}%'");

if ($result == TRUE) {
while ($row = mysqli_fetch_array($result))
{
        echo $row['year'] . " " . $row['model'] . " " . $row['color'] . " " . $row['license_plate'] . " " . $row['vin'] . " " . $row['reward'];
        echo "<br>";
}


    mysqli_close($con);
    }
    if ($result == FALSE){ echo "car was not found in our database"; }
    ?>

修改

这是我的表格:

<form method="post" action="search.php" id="Search">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>

我试着把它带到哪里,你输入你想要找到的东西,如果它存在,那么它会显示其他明智的细节,它会说没有找到,我不希望它们能够进行空白搜索并查看所有表格

希望我明白我想做什么

1 个答案:

答案 0 :(得分:1)

简单的方法是

if (mysqli_num_rows($result) > 0)  // if there is more than 0 entry
{
while ($row = mysqli_fetch_array($result))
{
        echo $row['year'] . " " . $row['model'] . " " . $row['color'] . " " . $row['license_plate'] . " " . $row['vin'] . " " . $row['reward'];
        echo "<br>";
}
}
else  // using an else statement is better than the second if
{
echo "car was not found in our database";
}
mysqli_close($con);

修改

如弗雷德的评论中所述,将表单更改为:

  <form method="post" action="search.php" id="Search">
     <input type="text" name="Search"/>
     <input type="submit" name="submit"/> 
  </form>