Tauras Tauras - 6 months ago 29
PHP Question

Select from table where field data 'like' variable

The script works just fine, but not as expected.

$table = $_POST['table'];
$field = $_POST['field'];
$condition = $_POST['condition'];
$value = $_POST['value'];

if ($condition == 'Contains') { $newcondition = 'like'; }

$builder = DB::table($table)->where($field, $newcondition, '%'.$value.'%')->get();

For example, my field data looks like this: A, B, C, D

It gives me correct results, if
is in same order: A, B (if value is in original order).

But it does not give results at all, if
is A, D or in different order.

How to make this script to work, if
is not in original order?


You can split the $value and create a custom whereRaw with AND for each individual value. I would also suggest that you examine whether or not it makes sense to be storing your data the way you have it saved, especially if the query you are making now is one you plan to make often. There might be much more efficient ways to store it.

$values = explode(', ', $value);
$query = "";
foreach($values as $param) {
    $query .= $field.' LIKE %'.$param.' AND' 
$query = rtrim($query, " AND");