-4

I have multiple ids separated by + in one field of a row in a table Like : (123+21654+412+12387)

I need Only EXACT MATCHES, (e.g.: only "123" and not "123 & 12387")

My code is like this:

$var = $value['id'];
$result = mysqli_query($this->dbh, "SELECT id FROM table
      WHERE id REGEXP '[[:<:]]$var[[:>:]]' ");

I have a problem with using a variable in REGEXP.

in case of :

$result = mysqli_query($this->dbh, "Select id FROM table
      WHERE id REGEXP '^$id|[\+]$id' ");

it works, but it does not return only exact matches

Rick James
  • 135,179
  • 13
  • 127
  • 222
iCode98
  • 41
  • 1
  • 7

2 Answers2

0

PHP tip: "Interpolation" works these ways:

  • "...$var[...]..." treats that as an array lookup for $var[...].
  • Without [, $var is assumed to be a scalar.
  • "...{$var}[...]..." is what you need

This last example has braces {} to tell PHP to evaluate what is inside without being concerned about what follows. More common usage:

$var = 'abc';
// I want to generate "abc123"
$bad  = "$var123";   // looks for variable 'var123'
$good = "{$var}123;  // correctly yields "abc123"

Your second attempt can be fixed thus:

REGEXP '(^|\+)$id(\+|$)'

meaning:

  1. At the beginning or after a +,
  2. Find $id (after interpolating),
  3. And stop with a + or the end of the string.
Rick James
  • 135,179
  • 13
  • 127
  • 222
-1

I'll go with :

$sql = "SELECT id FROM table WHERE id='123' OR id LIKE '123+%' OR id LIKE '%+123' OR id LIKE '%+123+%'";

The first condition will apply if you only have the value, the second if the field starts with the value, the third if the field ends with the value and the fourth if the value is in the middle of the field.

niiwig
  • 150
  • 4