【问题标题】:PHP string compare and search in a multiple table columnPHP字符串在多表列中比较和搜索
【发布时间】:2015-05-17 01:01:07
【问题描述】:

这是我的第一篇文章,我在使用 PHP 搜索时遇到了问题。

这里,

$searchq = $_POST['searchq'];

到目前为止,当为 searchq 提供单个单词(如 naresh、google、lamgade)时,它会在 db 中搜索,但当有多个搜索时,如

naresh lamgade 同时出现这些单词有错误,因为它只在 first_name 列中搜索,而我想在 first_name 列中搜索 naresh 并在 last_name 列中搜索 lamgade

这里是代码

<pre> $searchq = $_POST['searchq'];

 $conn = mysqli_connect('localhost','root','','std_info') or die("Cant' Connect to db");

 $query = mysqli_query($conn,"select * from student_details  where first_name like '%$searchq%' or last_name like '%$searchq%'");

 $count = mysqli_num_rows($query);    

 if($count == 0) {

         echo "<br>";
         echo "Can't find, try entering only first name or last name";

  }    
  else {
         do something`</pre>
   }

问题是

在搜索栏中,当我尝试输入 naresh lamgade 并搜索时

searchq =naresh+lamgade

它在 first_name 和 last_name 列中搜索 naresh+lamgade 所以没有结果。

我想知道,如何打破这两个词并用这些词在不同的列中搜索。

【问题讨论】:

标签: php mysql search


【解决方案1】:

使用explode拆分查询。 您的代码也很危险。使用 mysqli_escape_real_string 转义查询中的特殊字符:

<?php
$searchq = explode(" ", $_POST['searchq']);
$conn = mysqli_connect('localhost', 'root', '', 'std_info') or die("Cant' Connect to db");
$query = mysqli_query($conn, "select * from student_details  where (first_name like '%" . mysqli_real_escape_string($searchq[0]) . "%' OR first_name like '%" . mysqli_real_escape_string($searchq[1]) . "%') OR (last_name like '%" . mysqli_real_escape_string($searchq[1]) . "%' OR last_name like '%" . mysqli_real_escape_string($searchq[0]) . "%'");
$count = mysqli_num_rows($query);

if ($count == 0)
    {
    echo "
    ";
    echo "Can't find, try entering only first name or last name";
    }
  else
    {
    do something`

【讨论】:

    【解决方案2】:

    问题是
    在搜索栏中,当我尝试输入 naresh lamgade 并搜索时

    searchq =naresh+lamgade"
    

    我猜您将文本字段放在没有method="post" 的表单中。
    如果你这样做了,请在 searchq 中尝试这样:

    ... WHERE first_name LIKE "'%'.$searchq.'%'" or last_name like "'%'.$searchq.'%');
    

    【讨论】:

      【解决方案3】:

      感谢大家的回答,但我已经使用了这个查询,它可以按我的意愿完美运行。

      $query = mysqli_query($conn, "SELECT * FROM student_details WHERE CONCAT(first_name,' ',last_name) like '%$searchq%'");
      

      【讨论】:

        猜你喜欢
        • 2021-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多