我正在尝试为我的网站设置 PHP 高级搜索。 代码 php 是:
$sql = "SELECT * FROM users WHERE";
foreach($_POST AS $key => $value) {
if(count($_POST) > 0 && !empty($_POST[$key])) {
$value = clean_data($value);
$sql .= " $key LIKE '%{$value}%' OR ";
}
$sql = rtrim($sql,' OR ');
$res = mysqli_query($connection,$sql) or die(mysqli_error($connection));
$row = mysqli_fetch_assoc($res);
echo "<pre>";
print_r($row);
}
html代码是:
<form action="search.php" method="POST">
<h3>
Search for plate number
</h3>
<input type="text" name="name" placeholder="Enter name">
<input type="text" name="email" placeholder="Enter email">
<input type="text" name="car_model" placeholder="Enter car model">
<input type="submit" name="submit">
</form>
如果我提供姓名和电子邮件作为搜索词,我会得到这个:
<pre>
Array
(
[id] => 22
[name] => fname lname
[email] => whatever@hotmail.com
[plate_num] => 775hgy
[password] => 4194933072aab7975beb010542011ea1387d54b0
[gender] =>
[country] =>
[gov] =>
[cell_num] =>
[username] => username
[profile_pic_url] =>
[car_model] =>
[age] => 0
[location] =>
[job] =>
[license_pic_url] => plate_images/497002597df3168ebd6e2813f29b53ea.jpg
[android_key] => b0178e8f817cd6c9ec6b5a438633e634
[creation_date] => 2017-08-19 22:46:33
[modif_date] => 2017-08-19 22:46:33
[is_online] => 0
[num_friends] => 0
[activation_code] => b23f8f7cea65f5c1d003165e8f1f5c61
[account_stats] => 1
[user_ip] => ::1
)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'email LIKE '%what_i _entered_for_email%'' at line 1
我尝试了下面提供的所有解决方案,但没有成功。
我真的不知道哪里出了问题。有什么想法吗?
最佳答案
OR 问题,LIKE 运算符缺少单引号。尝试以下任何代码。
$sql = "SELECT * FROM users WHERE";
$i = 0; // loop count
foreach($_POST AS $key => $value) {
if(!empty($key)) {
$value = clean_data($value);
$sql .= ($i++ > 0 ? " OR " : "")." $key LIKE '%{$value}%' ";
echo "<br />".$sql; // print sql query and debug
$res = mysqli_query($connection,$sql) or die(mysqli_error($connection));
while ($row = mysqli_fetch_assoc($res)) {
echo "<pre>";
print_r($row);
}
}
}
或
$sql = "SELECT * FROM users WHERE";
foreach($_POST AS $key => $value) {
if(!empty($key)) {
$value = clean_data($value);
$sql .= " $key LIKE '%{$value}%' OR ";
echo "<br />".rtrim($sql,' OR '); // print sql query and debug
$res = mysqli_query($connection,rtrim($sql,' OR ')) or die(mysqli_error($connection));
while ($row = mysqli_fetch_assoc($res)) {
echo "<pre>";
print_r($row);
}
}
}
关于PHP 高级搜索错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45911599/