1

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?

CLiown
  • 13,665
  • 48
  • 124
  • 205
  • There are plenty of ways of doing this, but the right way is to use parameterized queries. Remember little Bobby Tables... http://xkcd.com/327/ – Ed Manet Apr 05 '12 at 17:38
  • Here's a great question on topic: http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php – Ed Manet Apr 05 '12 at 17:39

5 Answers5

0

Try wrapping in braces:

LIKE '%{$format}%'
Kasapo
  • 5,294
  • 1
  • 19
  • 21
0

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 . "%'");
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
0

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}%'"
SenorAmor
  • 3,351
  • 16
  • 27
0

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'");
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
0

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.

Starx
  • 77,474
  • 47
  • 185
  • 261