簡體   English   中英

如何根據搜索結果動態更改表中的數據?

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

我正在嘗試構建一個頁面,該頁面顯示在html表中搜索過的數據。 我在頁面上設置了搜索字段和按鈕,並在一個小表格中顯示了當前的所有數據。 我需要它來根據搜索字段中的單詞來主動更改表中顯示的數據。

編輯:

如何根據搜索字段中的文本動態更改表中的數據?

<?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`";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM