如何从数组值搜索到MySQL

时间:2019-07-18 03:01:42

标签: php mysql arrays

来自搜索框的变量包含(14409,14408,14405)。 我想在mysql中分别搜索其中的每个 如果发现其中之一正在获取数据,则不忽略它并显示按摩不存在

<form method="POST" class="form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
    <input type="text" name="vehiclenum" placeholder="Search Multiple Separate by a Comma (,)">
    <input type="submit" name="submit" Value="Search">
</form>
<?php
$vehiclenumerr = array();
if ($_SERVER['REQUEST_METHOD']=="POST"){
  $vehiclenum = $_POST["vehiclenum"];

$exploded=explode(",",$vehiclenum);
$explodedd=implode("','",$exploded) ;
$sql = "SELECT * FROM vehicles WHERE num_vehicles IN('$explodedd')";
$result = mysqli_query($conn, $sql);
$num_query = mysqli_num_rows($result);
if ($num_query > 0) { ?>
<table> 
<tr>
<th>Vehicle num</th>
<th>Description</th>
</tr>

<?php while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row['num_vehicles']; ?></td>
<td><?php echo $row['desc_vehicles']; ?></td>
</tr>
<?php   }   ?>
</table>

<?php 
} else { $vehiclenumerr[] ="Vehicle Number: ".$vehiclenum. " are NOT Exist";}

}

if(!empty($vehiclenumerr)){
foreach ($vehiclenumerr as $error) {
            echo $error; 
            echo "<br>";
        }
}

?>

我希望找到该表格有2个结果(分别为14409和14405) 注释的下面(车辆编号:14408不存在)

我获得了表成功,但没有不存在的音符。

2 个答案:

答案 0 :(得分:0)

希望这会有所帮助:

  <?php while($row = mysqli_fetch_assoc($result)) { ?>
    <?php if($row['num_vehicles'] && $row['desc_vehicles']): ?>
      <tr>
      <td><?php echo $row['num_vehicles']; ?></td>
      <td><?php echo $row['desc_vehicles']; ?></td>
      </tr>
    <?php else: ?>
      <tr>
      <td><?php echo "Not exist" ?></td>
      <td><?php echo "Not exist" ?></td>
      </tr>
    <php endif; ?>
  <?php   }   ?>

或者您可以删除“不存在”字段。

答案 1 :(得分:0)

感谢帮助 我找到了解决方案,所以我与您分享。

$vehiclenum = check_input($_POST["vehiclenum"]);
$exploded = explode(",",$vehiclenum); 
$countexploded = count($exploded);
for ($i = 0; $i < $countexploded; $i++) {
  if (!empty($exploded[$i])) {
    $sql = "SELECT * FROM vehicles WHERE num_vehicles='$exploded[$i]'";
    $result = mysqli_query($connect_db, $sql);
    $num_query = mysqli_num_rows($result);
    if ($num_query > 0) {
       while($row = mysqli_fetch_assoc($result)) { 
            // sort results here
       } 
    } else { $vehiclenumerr[] ="Vehicle Number: ".$exploded[$i]. " are NOT Exist";}
  }
}

编辑:我还添加了防止SQL注入的功能:

function check_input($data){
    $data=trim($data);
    $data=stripcslashes($data);
    $data=htmlspecialchars($data);
    return $data;
}