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条)

报告相同问题?