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

'repetition-operator operand invalid' from REGEXP with CONCAT

My SQL table structure looks like this

id available_sizes
1 S,M,L
2 L,XL
3 Small,Large
4 30,32,33

Here I want to filter all IDs which consist of M or L sizes. I tried this operation with CONCAT and REGEXP, I tried this statement with PHP

$stmt = $conn->prepare('SELECT * FROM table WHERE CONCAT(",", available_sizes, ",") REGEXP ",(?|?),"');

$param1 = "M";
$param2 = "L";

$stmt->bind_param("ss", $param1, $param2);
$stmt->execute();
$result = $stmt->get_result();

Bt it shows an error: ‘repetition-operator operand invalid’ from regexp query.

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

>Solution :

You may match with REGEXP against \b(M|L)\b. Build the entire alternation in PHP and then bind it to a placeholder in the MySQL query:

$stmt = $conn->prepare("SELECT * FROM table WHERE available_sizes REGEXP ?");
$params = array("M", "L");
$regex = "[[:<:]](" . implode("|", $params) . ")[[:>:]]";

$stmt->bind_param("s", $regex);
$stmt->execute();
$result = $stmt->get_result();

Note: On MySQL 8+, use the above with the following minor change:

$regex = "\\b(" . implode("|", $params) . ")\\b";
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