dtzhfb4869 2017-01-09 14:20
浏览 87
已采纳

如何创建多个单词搜索? SQL

We have made a search field where you can search for ingredients and find recipes. For now you can only type in 1 ingredient:

if (isset($_POST['search'])) {
$searchquery = $_POST['search'];


$query = mysql_query("SELECT * FROM opskrifter WHERE id IN 
(SELECT opskrifterid FROM ingredienser WHERE ing_name IN ('$searchquery'))") or die("search failed");

We want to be able to search for multiple ingredients in the same search field by seperating the ingredients with a "," or something like this.

Is there a simple way to make that happen ?

EDIT: We tried to use explode like this without succes.

$searchTerms = explode(' ', $searchquery);
$searchTermBits = array();
foreach ($searchTerms as $term) {
if (!empty($term)) {
    $searchTermBits[] = "ing_name '$term'";
}}

...
$result = mysql_query("SELECT * FROM opskrifter WHERE id IN (SELECT * FROM  WHERE ".implode(' AND ', $searchTermBits)));

Thanks! :)

  • 写回答

3条回答 默认 最新

  • dpa84373 2017-01-09 14:54
    关注

    You could simply get the user to type in his values comma-separated, the the input would be almost in the right syntax for the query. You just have to add semicolons around the values because you search for a string in your table.

    You can use PHP's str_replace()-Function:

    $vals = $_POST['search'];
    $valsFormatted = "'" . str_replace(",", "','", $vals) . "'";
    

    In this code, you replace all the commas of the input with the comma plus semicolons before and behind them in orderto wrap all values of the input with semicolons. You also have to add one at the beginning and at the end of the string. Replace the first comma in the function above with the char you want your users to separate the values with.

    After that, you can simply change your query to the following:

    $query = "SELECT * FROM opskrifter WHERE id IN 
    (SELECT opskrifterid FROM ingredienser WHERE ing_name IN ('$valsFormatted'))";
    

    Please also be informed, that your code like this is vulnerable for SQL Injections! Check out this link to learn how to prevent this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。