好的,所以基本上我想为某些网站产品建立一个简单的搜索系统。我的目标是确保用户每次搜索内容时,他/她只会看到标题与搜索字词匹配的项目。
这是我的代码产品页面代码:
<form action="search.php" id="search_form" name="search_form" method="post">
<div class="form-field">
<label for="search-field">Search</label>
<input type="search" name="search_form" />
<input type="submit" value="Search">
</div>
</form>
这是我的search.php代码:
<?php
include 'config.php';
$x = $_POST['search_form'];
$stmt = $conn->prepare("SELECT * FROM WHERE product_name='".$x."'");
$rowName = $row['name'];
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()):
?>
答案 0 :(得分:2)
SQL应该看起来像这样:
SELECT * FROM WHERE product_name LIKE '%socks%'
这将符合以下条件:
'socks for cats'
'green socks'
'knitted socks for giraffes'
更改PHP代码以使用LIKE
实现以上目的。
假设您正在使用PDO:
include 'config.php';
$x = '%' . $_POST['search_form'] . '%';
$stmt = $conn->prepare("SELECT * FROM WHERE product_name LIKE ?");
$stmt->execute([$x]);
while($row = $stmt->fetch()){
// do something with product data
}
mysqli
include 'config.php';
$x = '%' . $_POST['search_form'] . '%';
$stmt = $conn->prepare("SELECT * FROM WHERE product_name LIKE ?");
$stmt->bind_param("s", $x);
$stmt->execute();
$res = $stmt->get_result();
while($row = $res->fetch_assoc()){
// do something with product data
}