我在wordpress中创建了一个短代码,用户可以使用帖子标题或帖子的段码从帖子中提取信息。一切都很好,除了当一个帖子的标题中有一个撇号。
使用post段符的短代码的一个例子是
[card]hunters-mark[/card]
当我使用文章标题和标题有一个撇号它不工作。
[card]Hunter's Mark[/card]
当我使用短代码与不包含撇号的帖子标题时,一切都有效,所以问题是撇号。我用来获取post id的代码是
$sql="select * from $wpdb->posts where (post_title='$content' or post_name='$content' ) and post_type='cards' and post_status='publish' limit 0,1";
$my_posts = $wpdb->get_results($sql);
if( $my_posts ) {
$card_id = $my_posts[0]->ID;
}
编辑:那么奇怪的是,当我试图用
输出所有内容时`$data=strpos($content,"'");
var_dump($data);
$content=str_replace("'", "''", $content);`
显示strpos("Hunter's Mark","'")=false
所以它说没有'即使有,我检查了数据库和帖子标题显示了我是如何在短代码中拥有它的
显然不能自动转义引号。你需要自己做:
$sqlContent = mysqli_real_escape_string($content);
我还建议在变量中使用大括号。
$sql="select * from {$wpdb->posts} where (post_title='{$sqlContent}' or post_name='{$sqlContent}' ) and post_type='cards' and post_status='publish' limit 0,1";
$my_posts = $wpdb->get_results($sql);
...
<标题> 更新你可以用另一种(更安全的)方法:
$wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM {$wpdb->posts} WHERE
(post_title=%s OR post_name=%s)
AND post_type='cards' AND post_status='publish'
LIMIT 0,1",
$content,
%content
)
);
标题>您应该在查询中使用mysql_real_escape_string($content)
之前使用它,或者更好地使用准备好的语句来使事情更安全,目前您容易受到sql注入的攻击。如果您使用预处理语句,这个问题将得到解决,并且对您来说也将更安全。
https://codex.wordpress.org/Class_Reference/wpdb Protect_Queries_Against_SQL_Injection_Attacks
您应该使用$wpdb->prepare()
方法来正确地插入和转义您的变量-它也可以防止SQL注入。在SQL中使用%s
将表明您希望使用字符串,否则将使用%d
来表示数字。还建议在{$wpdb->posts}
周围使用花括号。因为你只是在寻找单行,你可能想使用get_row()
而不是get_results()
。如果你只想要ID
,你应该使用get_var()
和SELECT ID
。
global $wpdb;
// set up the SQL statement
$sql = "SELECT * FROM {$wpdb->posts} WHERE ( post_title=%s OR post_name=%s ) AND post_type='cards' AND post_status='publish' LIMIT 0,1";
// replace %s with $content
$query = $wpdb->prepare( $sql, $content, $content );
// query for results
$my_post = $wpdb->get_row( $query );
// did we get a result?
if ( ! empty( $my_post ) ) {
// get the ID
$card_id = $my_post->ID;
}