Use PHP variable in a SELECT LIKE query

123
November 25, 2018, at 6:40 PM

I'm trying to execute a mysqli query using the following code:

$sql = "SELECT * FROM `table` WHERE `description` LIKE ('AB CD %')";
$result= mysqli_query($con, $sql) or die(mysqli_error());

and this query gives me 6 results. It will only looks for items like "AB CD EF..." and not items like "AB CDEF...", which is exactly what I want. But if I give to the LIKE value a variable like this:

$var = "AB CD ";
$sql = "SELECT * FROM `table` WHERE `description` LIKE ('$var%')";
$result= mysqli_query($con, $sql) or die(mysqli_error());

it gives me zero results.

I have tried also several LIKE formats such ...('".$var."%')"; or CONCAT($var, '%'), but nothing.

How can get the same results as the first query usin a variable like in the sencond query?

The variable is get by a query which will select all description items and then, inside a while loop, it will look for the first Capital letters of each item:

$name = $row['description'];
$expr = '/[A-Z]*/';
preg_match_all($expr, $name, $res);
$var = implode(' ', $res[0]);

Each row has values like "AB CD EF something else in not capital letters"

Thank you.

Answer 1

How about this after wrapping the variable with curly braces {}? Also I just removed the extra parenthesis () after LIKE :)

$var = "AB CD ";
$sql = "SELECT * FROM `table` WHERE `description` LIKE '{$var}%'";
Answer 2

Well, user3783243 found the problem. When I implode the array to get the $var in a string, for some reason I cannot explain, the array elements (a lot of them) that had no value were included. The solution was to explode the $var, pass it through the array_filter function, to delete the empty elements and implode it again. Thank you all.

Answer 3

Use :

$var = "AB CD ";
$sql = "SELECT * FROM `table` WHERE `description` LIKE '".$var."%'";

But this is a bad practice as well as highly vulnerable, use prepared statement instead : http://php.net/manual/en/book.pdo.php

READ ALSO
Get Latitude Longitude from address in php

Get Latitude Longitude from address in php

I am developing an mobile application for ANDROID and IOSI want to get latitude , longitude from address pass by application to API

90
Dynamic row fields not inserted to mysql

Dynamic row fields not inserted to mysql

all I need a help, i've stuck latelyI have dynamic row field, so my user can add the fields dynamicaly

146
Is it possible to create blocks for builders without php? [on hold]

Is it possible to create blocks for builders without php? [on hold]

The question is resonant, but neverthelessHave you ever seen any visual Builder (or plug-in for it) on your practice that allows to create blocks for any Builder-without knowledge of php?

136
Laravel - Storing and Setting up Array in Controller

Laravel - Storing and Setting up Array in Controller

I am a beginner programmer in Laravel, please guide me through here thank you

121