gpt4 book ai didi

php 搜索框结果显示不正确?

转载 作者:行者123 更新时间:2023-11-29 09:25:43 25 4
gpt4 key购买 nike

我正在尝试使用以下代码创建一个 php 搜索框,但是当我按下提交时,它会显示 wallname 中的所有三个条目,而不是与搜索相关的条目。

php:

if (isset($_POST['submit-search'])){
$searchq= $_POST['search-input'];
$query = mysqli_query($conn, "SELECT wallname FROM walldb WHERE
wallname LIKE '%$searchq%'");
$result= mysqli_num_rows($query);
if ($result = 0){
echo "error search";
} else{
while($row = mysqli_fetch_assoc($query)){
$name = $row['wallname'];
$output = '<div>'.$name.'</div>';
print ("$output");
}
}
}

html:

 <form action= "" method= "post">
<button type= "submit" name="submit-search">Search</button>
<input id="search" name="search-input" type="text" placeholder="Search By Name"
autocomplete="off"><a href="#"><img id="cancle" src="/images/cancle.png"></a>
</form>

在搜索框中输入内容并按搜索后的结果:

win7-haystack
win10-iceland
win10-road

最佳答案

由于有很多关于使用prepared statements和PDO的评论,下面给出使用PDO的解决方案:

Read more about PDO here

$dsn = "mysql:host=YOUR_MYSQL_HOST;dbname=YOUR_DATABASE_NAME;charset=utf8mb4";
$options = [
PDO::ATTR_EMULATE_PREPARES => false, // turn off emulation mode for "real" prepared statements
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
$pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
error_log($e->getMessage());
exit('Could not connect to the database.');
}
$arr = [];
$searchq = "%{$_POST['search-input']}%";
$stmt = $pdo->prepare("SELECT wallname FROM walldb WHERE wallname LIKE ?");
$stmt->execute([$searchq]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$arr[] = $row;
}
if(!$arr) exit('No results found');

print_r($arr);

For extra reading: An article about preventing SQL injection using PDO

关于php 搜索框结果显示不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59637381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com