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

1

3 Answers 3

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.'%');
Sign up to request clarification or add additional context in comments.

Comments

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`

Comments

-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%'");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.