Wordpress php mysql LIKE query not working

2019-07-18 18:30发布

$db_item =  $wpdb->get_results($wpdb->prepare( "SELECT * FROM wp_wowhead_items WHERE name LIKE %s", "%". "Hello" . "%") );

This above one works... But the below one doesn't work!

$text = "Hello";
$db_item =  $wpdb->get_results($wpdb->prepare( "SELECT * FROM wp_wowhead_items WHERE name LIKE %s", "%". $text . "%") );

Where am I missing the syntax? I tried almost every combination with quotes, slashes, escapes...

3条回答
Root(大扎)
2楼-- · 2019-07-18 19:20

Escape it with double %%

When using get_results() in Wordpress, all % characters inside SQL string literals, including LIKE wildcards, must be double-% escaped as %%

$db_item = $wpdb->get_results($wpdb->prepare(

"SELECT * FROM wp_wowhead_items WHERE name LIKE '%%$text%%'"

));

查看更多
趁早两清
3楼-- · 2019-07-18 19:21

Try this:

$db_item =  $wpdb->get_results($wpdb->prepare(
    "SELECT * FROM wp_wowhead_items WHERE name LIKE %s", '%$text%'"
));
查看更多
你好瞎i
4楼-- · 2019-07-18 19:21

Wrap it in quotes:

$db_item =  $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM wp_wowhead_items WHERE name LIKE %s", "'%". $text . "%'"));
查看更多
登录 后发表回答