繁体   English   中英

使用php多字段搜索MySQL数据库

[英]Multiple Fields search MySQL database using php

我快到了,我的代码没有显示任何结果。
这是用户按邮政编码和物业类型进行搜索的基本形式。
他们应该能够通过仅输入邮政编码或同时输入两者来进行搜索。
我在本地主机 php7 中工作
这里的html

<form action="phpSearch.php" method="post">
    <input type="text" placeholder="Search" name="postcode" id="postcode">
    <select name="type" id="type">
        <option value="Terraced">Terraced</option>
        <option value="Detached">Detached</option>
    </select>
    <button type="submit" name="submit">Search</button>
</form>

这里的php

<?php
$postcode = $_POST['postcode'];
$type = $_POST['type'];


$servername = "localhost";
$username = "root";
$password = "";
$db = "priceverification";

$conn = new mysqli($servername, $username, $password, $db);

if ($conn->connect_error){
    die("Connection failed: ". $conn->connect_error);
}

$sql = "SELECT * from house WHERE $type like '%$postcode%'";

$result = $conn->query($sql);
  if($result){
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
    echo $row["postcode"]."  ".$row["type"]."  ".$row["town"]."<br>";
}
} else {
    echo "0 records";
}
 }else {
                echo "<br> Database error.";
            }
$conn->close();
?>

数据库在这里

由于多种原因, $type like '%$postcode%'是无效代码。 您需要根据来自表单的值构建搜索条件。

以下是代码的正确外观:

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli("localhost", "root", "", "priceverification");
$conn->set_charset('utf8mb4'); // always set the charset

$postcode = $_POST['postcode'] ?? '';
$type = $_POST['type'] ?? '';

$wheres = [];
$values = [];
if ($postcode) {
    $wheres[] = 'postcode LIKE ?';
    $values[] = '%'.$postcode.'%';
}
if ($type) {
    $wheres[] = 'type = ?';
    $values[] = $type;
}
$where = implode(' AND ', $wheres);
if ($where) {
    $sql = 'SELECT * from house WHERE '.$where;
} else {
    $sql = 'SELECT * from house';
}

$stmt = $conn->prepare($sql);
$stmt->bind_param(str_repeat('s', count($values)), ...$values);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    foreach ($result as $row) {
        echo $row["postcode"] . "  " . $row["type"] . "  " . $row["town"] . "<br>";
    }
} else {
    echo "0 records";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM