繁体   English   中英

如何在MySQL数据库中查询PHP $ _GET数组

[英]How to Query MySQL Database for PHP $_GET Array

我正在尝试创建一个简单的搜索字段,用户可以在其中编写文本。 此文本被传输到php,然后通过GET访问该文本。 如果文本包含空格,则将其转换为数组。 问题是我无法弄清楚如何使用数组作为Where条件查询条目。 我尝试了一些答案,例如implode(“,”,$ array)或WHERE IN($ array)。 他们都没有为我工作。 我得到数组到字符串比较错误或未知列错误。 $ _GET数组包含表单提交的字符串,因此不是错误。

谢谢你的帮助!

PHP脚本

//string containing the submitted searchbox value
$query=$_GET['Searchquery'];

//Seperate string where whitespaces are detected and create array holding these strings
$querystring=explode(" ",$query);
//Connection
$con=new mysqli($Server,$User,$UserPassword,$Database);



//print_r for testing
print_r($querystring);

//That's the problem
$sql="SELECT * FROM tb_user WHERE ??????"



if($result=$con->query($sql))
{
$word;

//Check if query result is one or multiple entries
  if($result->num_rows==1)
$word="entry";
else
$word="entries";


//output_____________
  echo("<h1>We found ".$result->num_rows." ".$word." meeting your Keyword '".$query."'</h1>");

  while($row=$result->fetch_assoc())
  {


echo("<div id='founduser'><a href='profile.php?ProfileLink=".$row['ProfileLink']."'><h1>".$row['GivenName']." ".$row['FamilyName']."</h1></a></div>");





  }



}
//______________________________
else {
  echo($con->error);

}






 ?>
$sql="SELECT * FROM tb_user WHERE column_name IN ('".implode("','", $querystring)."')";


implode()explode()相反。 它将使用提供的字符串将数组的所有索引连接在一起。 如果从查询中提取implode ,则会得到如下所示的内容:

item1','item2','item3

从那里,我们几乎错过了第一项和最后一项的外引号,因此我们可以将它们添加到查询中,如上所示。

上面的查询将生成为:

SELECT * FROM tb_user WHERE column_name IN ('item1','item2','item3')

IN子句检查以查看提供的值是否与给定列中的任何值匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM