Search code examples
mysqlformssearchexplodeimplode

PHP explode and MySQL query to search in multiple columns


I have a form where I want a user to enter one or more words. These words should then match mutiple columns in a MySQL database.

I have started to build some code but I'm stuck.

<?php
  $term = $_SESSION['session_searchstring']; //Let's say that session is John Doe
  $searchterm = explode(' ',$term);

  $searchFieldName = "name";
  $searchCondition = "$searchFieldName LIKE '%" . implode("%' OR $searchFieldName LIKE '%", $searchterm) . "%'";

  $sql = "SELECT * FROM students WHERE $searchCondition;";

  echo $sql; //Echo to test what mysql_query would look like

?>

The above code will output:

SELECT * FROM students WHERE name LIKE '%John%' OR name LIKE '%Doe%'; 

The problem is that I want to search in multiple columns ($searchFieldName). I have for example

customer_firstname
customer_lastname

And I want to match my searchstring against the content of both columns.. How would I continue?


Solution

  • Perhaps

      $term = $_SESSION['session_searchstring']; //Let's say that session is John Doe
      $searchterm = explode(' ',$term);
    
      $searchColumns = array("customer_firstname","customer_lastname");
    
      for($i = 0; $i < count($searchColumns); $i++)
        {
            $searchFieldName = $searchColumns[$i];
            $searchCondition .= "($searchFieldName LIKE '%" . implode("%' OR $searchFieldName LIKE '%", $searchterm) . "%')";
            if($i+1 < count($searchColumns)) $searchCondition .= " OR ";
         }
    
      $sql = "SELECT * FROM students WHERE $searchCondition;";
    
      echo $sql; //Echo to test what mysql_query would look like
    

    Produces

    SELECT * FROM students WHERE (customer_firstname LIKE '%John%' OR customer_firstname LIKE '%Doe%') OR (customer_lastname LIKE '%John%' OR customer_lastname LIKE '%Doe%');