doudong4532 2012-01-10 17:33
浏览 85
已采纳

如何“分割”在表单上的文本字段中输入的单词,并根据数据库查询每个单词

In index.php I have a form and in the form a text field:

<form name="UserSearch" action="petSearch.php" method="GET">
     <input type="text" name="petWish" value="" />
</form>

where the user enters what pets they want into the text box (seperated by commas) e.g dog, cat, fish, snake

In petSearch.php, I use the following function to create a legal SQL string that can be used in a SQL statement:

<?php    
    $userPetWish = mysqli_real_escape_string($link, $_GET["petWish"]);
?>

I then create the SQL statement and query the MySQL database:

<?php
    $query="SELECT petType, name, age FROM pets WHERE petType LIKE '%".$userPetWish."%'";
    $result = mysqli_query($link, $query);

      if($result)
      {
          while($row = mysqli_fetch_array($result))
          {
             echo "From the pets you entered we have" . $row[petType] . "," . $row[name] . "," . $row[age];
          }
      }
      else
      {
         echo "Sorry we do not have any of your chosen pets in store";
      }
?>

So my question is:

1) In order to search for each individual pet against the database, is it possible to 'split' the pets which the user entered by commas and then query the Pet table in the database using the "LIKE" function? If so, can you tell me how to structure this?

2) If after doing the search against the database there is a dog, cat and fish in store, but no snake. How do i get it to display this, to show the petType, name and age they have of the three pets, but not the snake? (I'm not sure if the way I structured this in the while loop is correct)

  • 写回答

2条回答 默认 最新

  • dqroktbn005028 2012-01-10 17:37
    关注

    You can use

    explode( ',', $userPetWish )
    

    to split the words up.

    Also a note I would use

    echo 'From the pets you entered we have' . $row['petType'] . ',' . $row['name'] .
        ',' . $row['age'];
    

    Instead of no quotes within the $row;

    Also your better of stripping the slashes strip_slashes ( $userPetWish ) if your using a LIKE otherwise your going to get slashes in the query and might break it ( may be wrong, just what ive experienced )

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么