0

How to add a PHP variable inside REGEXP in mySQL

My code is like this

SELECT count(product_id) as totalCount FROM ref_products WHERE misc REGEXP '(.*\"level_id\":\'".$course_level_id."'\.*)'     
1
  • And what happens then.?Is there any error.? Commented Dec 11, 2013 at 12:35

3 Answers 3

1

Assuming you use a double quoted string ("):

$sql = "SELECT count(product_id) as totalCount FROM ref_products WHERE misc REGEXP '(.*\"level_id\":\'".$course_level_id."'.*)'";

Assuming you use a single quoted string ('):

$sql = 'SELECT count(product_id) as totalCount FROM ref_products WHERE misc REGEXP \'(.*\"level_id\":'.$course_level_id.'.*)\'';
Sign up to request clarification or add additional context in comments.

4 Comments

This is working perfect in database. so i will use a dynamic variable in php as $course_level_id. Instead of "20" i have to give the variable. SELECT * FROM ref_products WHERE misc REGEXP '(.*\"level_id\":\20\.*)'
Its not a double quote string
Added the single quote sql as well
Might be needed to escape the double quotes in there. Updated answer
1

Thanks to all guys for their time & effort. Here is the correct answer i found. Please check

SELECT count(product_id) as totalCount FROM ref_products WHERE misc REGEXP '(.*\"level_id\":$course_level_id.*)'

Comments

0
SELECT count(product_id) as totalCount FROM ref_products WHERE misc REGEXP '(.*"level_id":"'.$course_level_id.'".*)'  

5 Comments

@RIADev: not working is not very descriptive. We don't know what you're thinking or the output you're getting -- we only know what you're telling us. So, please be descriptive and explain the issue.
Sorry..This is working perfect in database. so i will use a dynamic variable in php as $course_level_id. Instead of "20" i have to give the variable. The query is like this SELECT * FROM ref_products WHERE misc REGEXP '(.*\"level_id\":\20\.*)'
@Amal Any upadtes from you ??
You are using quotes wrongly. Correct format: '(.*"level_id":'. $course_level_id.'.*)'
@nick In php it showing error near '(.*"level_id":' --- Undefined level_id. So we need to escape the double quote. Refer my answer its working perfect. If you have any quotes then refer ronald answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.