我创建了一个搜索栏,用户可以在其中输入关键字,表单php代码会爆炸输入以形成一个单词数组。然后我使用foreach循环遍历单词列表并在我的数据库中的两个表中搜索匹配短语。
主要功能如下:
两周前一切都运行良好但现在出于某种原因,当我以管理员身份登录时搜索多个关键字时会抛出错误。我已经广泛检查了我的代码,并且我尝试对其进行更改,但它仍然无法正常工作。下面是我出现的mysql_error:
您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在“OR fname LIKE”%string%'或lname LIKE'%string%'附近使用正确的语法,或者在第1行发送LIKE'%string%'或ma'的电子邮件
以下是我的代码:
if(empty($_POST)=== false){
require ('core/dbconnection.php');
$output = '';
$error = '';
$input = mysql_real_escape_string($_POST['search_input']);
$i=0;
if($input){
$keyword = explode(" ", $input);
if($admin == 1){
//If a user is logged in and the user is an Admin.
$search_items = "SELECT * FROM ecom_products WHERE ";
$search_users = "SELECT * FROM ecom_users WHERE ";
foreach($keyword as $k){
$k = mysql_real_escape_string($k);
$i++;
if($i == 1){
$search_items .= "name LIKE '%$k%' OR description LIKE '%$k%'";
$search_users .= "is_admin='1' AND (fname LIKE '%$k%' OR lname LIKE '%$k%' OR email LIKE '%$k%' OR main_tel LIKE '%$k%'";
}else{
$search_items .= " OR name LIKE '%$k%' OR description LIKE '%$k%'";
$search_users .= " OR fname LIKE '%$k%' OR lname LIKE '%$k%' OR email LIKE '%$k%' OR main_tel LIKE '%$k%'";
}
$search_users .= ") ORDER BY lname DESC";
}
PS。我正在将我的所有“msql”扩展更新为“mysqli”,实际上我尝试了mysqli,它甚至没有运行查询,所以我想在更改我的mysql exntensions之前解决这个问题。非常感谢您的帮助
答案 0 :(得分:2)
你需要移动
$search_users .= ") ORDER BY lname DESC";
在foreach($keyword as $k)
循环之外。现在它在每个循环结束时添加,因此您的查询将如下所示
SELECT * FROM ecom_users WHERE
is_admin='1' AND (fname LIKE '%$k%' OR lname LIKE '%$k%' OR email LIKE '%$k%' OR main_tel LIKE '%$k%'
) ORDER BY lname DESC
OR fname LIKE '%$k%' OR lname LIKE '%$k%' OR email LIKE '%$k%' OR main_tel LIKE '%$k%'
) ORDER BY lname DESC
应该是
foreach($keyword as $k){
$k = mysql_real_escape_string($k);
$i++;
if($i == 1){
$search_items .= "name LIKE '%$k%' OR description LIKE '%$k%'";
$search_users .= "is_admin='1' AND (fname LIKE '%$k%' OR lname LIKE '%$k%' OR email LIKE '%$k%' OR main_tel LIKE '%$k%'";
}else{
$search_items .= " OR name LIKE '%$k%' OR description LIKE '%$k%'";
$search_users .= " OR fname LIKE '%$k%' OR lname LIKE '%$k%' OR email LIKE '%$k%' OR main_tel LIKE '%$k%'";
}
// REMOVE FROM HERE
}
// PLACE HERE
$search_users .= ") ORDER BY lname DESC";