Using like statement with $wpdb->prepare showing hashes where wildcard characters are

℡╲_俬逩灬. 提交于 2020-05-27 12:05:44

问题


I'm trying to build a prepared statement with wildcards however I'm running into an issue where the percentage wildcard characters seem to be returning what seem to be hashes for the wildcards and I'm not sure why. The code in question is:

$condition = $wpdb->prefix."posts.post_title LIKE %%%s%%";
$query['conditions'][] = $wpdb->prepare($condition, $name);

And the results are:

posts.post_title LIKE {d690dd63f5944b9bca120e110c22802f0ec841d8120d813dd4abc08cba4a59c0}BT{d690dd63f5944b9bca120e110c22802f0ec841d8120d813dd4abc08cba4a59c0}

Just wondered if anyone had any ideas on what could be causing this. Any help would be greatly appreciated.

Thanks


回答1:


Don't worry about the hashes, they'll get replaced with % in $wpdb when you execute your query.

These hashes were introduced with WP v4.8.3 as a fix for SQL injection attack.

They're placeholders for the % character. It prevents someone from using something other than %s, %d, and %f. If there's a % other than those approved uses, it'll replace the % with a hash. That hash will get replaced back to % when $wpdb executes the query.

If you want to remove the hashes yourself, you can use remove_placeholder_escape(), like so:

$query['conditions'][] = $wpdb->remove_placeholder_escape($wpdb->prepare($condition, $name));




回答2:


The wildcard for LIKE must be within whatever variable is being denoted by %s. Otherwise it's getting the token for the parameter mixed up with the SQL wildcard. Even if that wasn't an issue, you need to do it like that anyway because otherwise the % won't be escaped within the string and you'll end up with a SQL syntax error.

In other words you need to add the wildcards to the $name value itself. This should do the job, I think:

$condition = $wpdb->prefix."posts.post_title LIKE %s";
$name = '%'.$name.'%';
$query['conditions'][] = $wpdb->prepare($condition, $name);


来源:https://stackoverflow.com/questions/53831586/using-like-statement-with-wpdb-prepare-showing-hashes-where-wildcard-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!