php 代码从 php 表单输入搜索单个字段并显示 mysql 数据库中的所有行

问题描述 投票:0回答:1

我发现这个 php 代码可以从 mysql 数据库中的 php 表单输入中搜索多个字段,并以相同的表单显示结果。

代码:

//search
if(isset($_POST['search']))
{
    $info = getData();
        $search_query="SELECT * FROM bike_in WHERE vin LIKE '%$info[1]%'";
    $search_result=mysqli_query($conn, $search_query);
        if($search_result)
        {
            if(mysqli_num_rows($search_result))
            {
                while($rows = mysqli_fetch_array($search_result))
                {
                    $vin = $rows['vin'];
                    $motor = $rows['motor'];
                    $battery1 = $rows['battery1'];
                    $battery2 = $rows['battery2'];
                        $model = $rows['model'];
                        $colour = $rows['colour'];
                        $lot = $rows['lot'];
                        $date_in = $rows['date_in'];
                    }
                } else {
                echo("no data are available");
                               }
                } else{
            echo("result error");
                }

} 

当我输入搜索值时,我必须输入所有 8 个字段,但我只想从 1 个字段(vin)进行搜索,当我点击“搜索”按钮时,我希望它显示与该字段相关的所有字段“文”。

插入VIN后,点击“搜索”按钮会要求用户输入“电机”。

即使只有“1”作为值,这种情况也会发生,直到所有 8 个字段都被填写为止。

这是我搜索得到的结果。(正确)

我希望能够只输入“VIN”字段,当我点击“搜索”按钮时,会显示与此 VIN 相关的所有 8 个值。

感谢 PHP 大师。

php
1个回答
0
投票

简短回答:

从每个字段中删除“必填”属性。

解释

这与PHP无关,您在PHP中正确搜索VIN。浏览器会生成“此字段为必填”错误,因为您向每个字段添加了“必填”属性。

您需要从每个字段中删除必需的属性,并在创建/更新记录时使用后端验证。如果您仍然喜欢使用客户端验证,则需要使用 JavaScript。

您可以手动执行验证,也可以完全删除 HTML 表单提交并使用 AJAX 搜索 VIN #。

这里有两个不同的例子来说明这一点:

使用 JavaScript 进行验证

<input type="text" name="vin" id="vin" > <!-- Remove "required" from all fields" -->

<button type="submit" onclick="add()">Add</button>
<button type="submit" onclick="search()">Search</button>

<script>
function add() {
  // Validate all fields here
  let vin = $("#vin").val(); // assuming you use jQuery.
  if (vin == "" || vin == null) {
    // display error
    window.event.preventDefault();
    return;
  }
  // repeat for all fields
}
</script>

使用AJAX进行搜索

<!-- Replace type="submit" by type="button" in search button -->
<button type="button" onclick="search()">Search</button>

<script>
async function search() {
   // get the vin number
   let res = await fetch("products/getdata?vin=" + vin);
   let data = await res.json();
   motor.value = data.motor;
   // repeat for all fields
}
</script>
© www.soinside.com 2019 - 2024. All rights reserved.