April 6, 2012

php mysql query – output value of variable in the query

Question by CLiown

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?

Answer by Starx

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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!