-1

its my first post and I have a problem with a PHP search.

Here,

$searchq = $_POST['searchq'];

so far when a single word is supplied for searchq like naresh, google, lamgade then it search in a db but when there is a multiple search like

naresh lamgade at a same time then there is error for these word because it only search in a first_name column and what i want to search naresh in a first_name column and lamgade in a last_name column

Here is the code

<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>
   }

The problem is

In a search bar, when i try entering naresh lamgade and search then

searchq =naresh+lamgade

and it search in both first_name and last_name column with a naresh+lamgade so there is no result.

I want to know , how to break these two words and search in a different column with these words.

JH_
  • 406
  • 1
  • 4
  • 15
nare
  • 1
  • 5
  • 1
    Use explode function to explode search terms. That would be a start. Something like this : http://stackoverflow.com/a/3621376/3402095 – Whirlwind Mar 14 '15 at 16:05

3 Answers3

1

The problem is
In a search bar, when i try entering naresh lamgade and search then

searchq =naresh+lamgade"

I guess that you put the textfield inside a form without method="post".
If you did, try like this in searchq:

... WHERE first_name LIKE "'%'.$searchq.'%'" or last_name like "'%'.$searchq.'%');
Joe Kdw
  • 2,245
  • 1
  • 21
  • 38
0

Use explode to split query. Also your code is dangerous. Use mysqli_escape_real_string to escape special characters in a query:

<?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`
Gncgroup
  • 26
  • 3
-1

Thanks everyone for the answer but I have used this query and it's working perfectly as I wanted.

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