Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a MYSQL query from results of splitting a string and using LIKE to match keywords in PHP

I am trying to split a string into an array and use these as keywords to make an sql query. I have made a sample of splitting the array and building the sql query. It sort of works but it is giving every table as a result but when I hard copy the built query it comes up with expected results.

This is what I have so far –

The string of keywords split into array and the query is built.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The db is called ‘clients_personal’ and the table is called ‘likes’

$my_search = "paper, glue, discount, bulk";
$new_search = preg_split("/,/", $my_search);
$mmsql = "SELECT * FROM clients_personal WHERE likes LIKE '%offers%'";

foreach ($new_search as $value) {
  $mmsql = $mmsql." OR likes LIKE '%$value%'";
}

No that results something like :

$mmsql="SELECT * FROM clients_personal WHERE likes LIKE '%offers%' OR likes LIKE '%paper%' OR likes LIKE '%glue%' OR likes LIKE '%discount%' OR likes LIKE '%bulk%'";

Now if I search like this, I get all the rows in the db?

$sql = "$mmsql";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    $id=$row["id"];

echo $id;
}
}

But if I query is as hard coded it gives predicted results?

$sql = "SELECT * FROM clients_personal WHERE likes LIKE '%offers%' OR likes LIKE '%paper%' OR likes LIKE '%glue%' OR likes LIKE '%discount%' OR likes LIKE '%bulk%'";
$result = $conn->query($sql);

I have a feeling its to do with quotes and i have tried removing them but no good? Any advice?
Also I an using this type of search as I found it on here.

>Solution :

The problem is here $new_search = preg_split("/,/", $my_search); use $new_search = preg_split("/, /", $my_search); instead.

The items in the string are separated by a comma and a space (", ") so you should split the string with that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading