简体   繁体   中英

php mysql query - output value of variable in the query

I have the following mysql query in php:

$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE '%details%'");

However I want the query to be dynamic by changing the LIKE section of the query. Instead of:

LIKE '%details%'

I want to put a variable in there:

LIKE '% $format %'

where $format is a string.

Everything I have tried thus far has failed.

Whats the proper way to do this?

Try wrapping in braces:

LIKE '%{$format}%'

Since you are using double quotes you could simply do:

$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE '%$format%'");

Or simply concatenate the string:

$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE '%" . $format . "%'");

Your string is already in double quotes, so just surround your variable with curly braces and you should be good to go.

"SELECT * FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE '%{$format}%'"

Before passing the variable do this

$format = '%' . $format . '%';
now simply put it in the query.

$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE '$format'");

You already got the answer. I can do it exactly like you want.

$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE '%$details%'");

Since the query is wrapped in double quotes, you dont need to escape anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM