在WordPress中使用wpdb查询没有结果

时间:2019-06-23 作者:stefanosn

除非我将字符串标题改为“Gocomma 10W QI无线快速充电器车载支架”,否则我不会得到任何结果。。。

   $title1="Gocomma 10W QI Wireless Fast Charger Car Mount Holder - 2pcs (it)";  

     $sql = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_title LIKE \'%%%s%%\' and post_status=\'publish\'",$title1);

     $post_if = $wpdb->get_results($sql);
感谢您的帮助!

编辑:

Well i had to save the text from $title1=get_the_title(); to .txt file and i noticed that the – saved as – in the txt file ...then i replaced str_replace("–","-","Holder – 2pcs") and it works! the problem is that in my wordpress databse the title contains - char as it should but then when i use get_the_title(); function of wordpress in my code to retrieve the title i get the - char as – which is eventually – i dont know why get_the_title(); causing this issue! any thoughts?

1 个回复
SO网友:Krzysiek Dróżdż

首先,您错误地转义了该查询。。。您应该使用esc_like 在类似部分和prepare 应该使用稍微不同的:

$title1 = \'Gocomma 10W QI Wireless Fast Charger Car Mount Holder - 2pcs (it)\';
$sql = $wpdb->prepare(
           "SELECT * FROM {$wpdb->posts} WHERE post_title LIKE %s AND post_status = \'publish\'",
           \'%\' . $wpdb->esc_like($title1) . \'%\'
       );
$post_if = $wpdb->get_results( $sql );
但这种方法还有一个问题。有可能- 字符转换为其他字符(如 - 破折号)等。