If your database column is a list of comma separated values, and you're searching for one value in that list, then you're in a different situation.
If your category
column contains the text value 410,406,149,152
, like you commented below, and you're searching for fields whose category
contains 152
, then you'll need to use MySQL's FIND_IN_SET()
function.
If you have to check multiple values, then you need to use more than one FIND_IN_SET
. If you read the documentation, you'll see that the first argument for FIND_IN_SET
must be a single string, not a string list (it can't contain a comma). Use the following instead:
$var = "401,320,152";
$items = explode(",", $var);
foreach ($items as &$i) {
$i = "FIND_IN_SET('" . $i . "', `category`)";
}
$search = implode(" OR ", $items);
unset($i);
$query = "SELECT * FROM business_listings WHERE " . $items;
This will output:
SELECT * FROM business_listings WHERE
FIND_IN_SET('401', `category`) OR
FIND_IN_SET('320', `category`) OR
FIND_IN_SET('152', `category`)
The above script will work even if $var
contains only one value.
Finally, as tadman mentioned, since we're getting into queries that can be tricky to build with prepared statements, you need to make sure you're escaping and sanitizing your input properly. For an example, if $var
is being retrieved from the user somehow, then before you modify it in any way, you need to escape it with mysqli_real_escape_string()
:
$var = $mysqli->real_escape_string($var);
Assuming that $mysqli
is your open MySQLi connection.
Hope this helps!