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 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了