[英]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.