Search code examples
phpmysqlcontainssql-like

How to search in mysql for a word that contains in a PHP variable?


I have multiple variables that contains customer names and looks like for example as below:

$customer =  $row["customer_name"];

This will contain i.e.: test Microsoft test test test

Now, in my database I have the column customer and the column contains Microsoft Netherlands Office

To look into the database, I have like below but it doesn't give me any results:

$query="SELECT * FROM specific_req WHERE customer LIKE '%$customer%'";

I want to search in the database table that contains any word from $customer.


Solution

  • You can use fulltext search i.e. MATCH AGAINST.

    $query="SELECT * FROM specific_req WHERE MATCH(customer) AGAINST ('$customer')";
    

    To make full text work, you will have to create FULLTEXT INDEX on customer column.

    ALTER TABLE specific_req ADD FULLTEXT KEY `idx_customer` (`customer`)
    

    Note: Sanitize $customer to avoid sql injection