如何根据搜索结果动态更改 table 中的数据?

How can I dynamically change the data in a table depending on search results?

我正在尝试构建一个页面来显示在 html table 中搜索到的数据。我在页面上设置了搜索字段和按钮,还有一个小 table 显示当前所有数据。我需要它根据搜索字段中的单词主动更改 table 中显示的数据。

编辑:

如何根据搜索字段中的文本动态更改 table 中的数据?

<?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "database name";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT clientname, clientsurname, address1, postcode, dob FROM clients";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        echo "<table><tr><th>Name</th><th>Surname</th><th>Address</th><th>Postcode</th><th>Date of Birth</th></tr>";
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "<tr><td>".$row["clientname"]."</td><td>".$row["clientsurname"]."</td><td>".$row["address1"]."</td><td>".$row["postcode"]."</td><td>".$row["dob"]."</td></tr>";
        }
        echo "</table>";
    } else {
        echo "There are 0 clients in the system matching your search criteria";
    }
    $conn->close();
    ?> 

最好的解决方案是向后端创建一个 ajax 请求,搜索数据库并返回一个 json 响应,该响应将附加到您的 html 中。

然而,这需要重构您的代码并拆分前端和后端逻辑。

@eselskas 所说 + 如果您想从搜索栏中按给定值进行搜索,则需要更改查询。

$sql = "SELECT clientname, clientsurname, address1, postcode, dob FROM `clients` WHERE `your_field` LIKE '%$_POST[search_var]%'";

或更好:

if($_POST['change_var'] != ""){
   $sql = "SELECT clientname, clientsurname, address1, postcode, dob FROM `clients` WHERE `your_field` LIKE '%$_POST[search_var]%'";
}else{
   $sql = "SELECT clientname, clientsurname, address1, postcode, dob FROM `clients`";
}