我在查询结束时使用了一个内爆,并且代码在直接传递的值下正常工作,但是如果$_POST
收到的值则没有。这是在行末SQL query. Syntax error
末尾使用implode和concatenate的正确方法。
$myquery = "SELECT * FROM `logins` WHERE ".implode(' OR ',$searchTermBits)." ";
上述格式在传递动态输入时是正确的。
<?php
$username = "xxxx";
$password = "xxxx";
$host = "xxxx";
$database = "xxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$search = $_POST["deskey"];
$search = explode(" ", $search);
$commonwords = "a,an,and,I,it,is,do,does,for,from,go,how,the,etc,in,on,are";
$commonwords = explode(",", $commonwords);
foreach ($search as $value)
{
if (!in_array($value, $commonwords))
{
$query[] = $value;
}
}
$query = implode(" ", $query);
$searchTerms = explode(" ", $query);
$searchTermBits = array();
foreach ($searchTerms as $term)
{
$term = trim($term);
if (!empty($term))
{
$searchTermBits[] = "description LIKE '%$term%'";
}
}
$myquery = "SELECT * FROM `logins` WHERE " . implode(' OR ', mysql_real_escape_string($searchTermBits)) . "";
$query = mysql_query($myquery);
if (!$query)
{
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++)
{
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
答案 0 :(得分:0)
在您的代码中,您只使用字段值。您还需要该字段的密钥才能从中获取MySQL:
$myquery = "SELECT * FROM `logins` WHERE 0"
foreach($searchTermBits as $key => $value){
$myquery .= " OR $key = '$value'";
}
Where 0
对$searchTermBits
为空的情况很重要。您仍将获得有效的SQL语句,即使它不会返回任何内容。
这不包括转义和检查用户输入的喷气机。我假设你自己这样做,因为它不是问题的一部分。
修改强>
在评论中提问:&#34;你可以指定你通常可以从$ _POST字符串中获得什么吗?&#34;
$_POST
通常是一个数组,由这些键的键和值组成。在这种情况下,键可能是您要搜索的字段以及您希望该字段的值。
使用这样的数组:
$_POST = array(
"name" => "muster",
"place" => "LA"
);
你的SQL最终会像这样:
SELECT * FROM `logins` WHERE 0 OR name = 'muster' OR place = 'LA'
答案 1 :(得分:0)
试试这个:
$search = array("name" => "muster", "place" => "LA"); //$_POST['search'];
$searchTermBits = Array();
foreach($search as $key => $value){
$searchTermBits[] = $key." = '".$value."'";
}
$myquery = "SELECT * FROM 'logins' WHERE ".implode(' OR ',$searchTermBits)." ";
echo $myquery;
返回的查询是
SELECT * FROM 'logins' WHERE name = 'muster' OR place = 'LA'