我创建了一个带有新表的插件(wp_soundcloud
) 我需要从新表中检索数据以及post数据。
以下是我的疑问:
$querystr = "
SELECT $wpdb->posts.*,
FROM $wpdb->posts
LEFT JOIN $wpdb->soundcloud ON($wpdb->posts.ID = $wpdb->soundcloud.idpost)
WHERE $wpdb->posts.post_type = \'soundcloud\'
AND $wpdb->posts.post_name = \'$name\'
";
$pageposts = $wpdb->get_results($querystr, OBJECT);
…下面是调试:
["last_query"]=>
string(176) "
SELECT wp_posts.*, .*
FROM wp_posts
LEFT JOIN ON(wp_posts.ID = .idpost)
WHERE wp_posts.post_type = \'soundcloud\'
AND wp_posts.post_name = \'test-demo\'
"
…以及错误:
["last_error"]=>
string(226) "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'FROM wp_posts
LEFT JOIN ON(wp_posts.ID = .idpost)
WHERE wp_posts.post_\' at line 2"
问题是
LEFT JOIN ON(wp_posts.ID = .idpost)
. 但为什么查询没有
JOIN
桌子?
最合适的回答,由SO网友:kaiser 整理而成
始终避免/准备您的数据,不要让它对注射开放:
global $wpdb;
$all_posts = $wpdb->get_results( $wpdb->prepare(
"
SELECT %s.*
FROM %s
LEFT JOIN %s ON(%s = %s)
WHERE %s = \'soundcloud\'
AND %s = \'%s\'
"
,$wpdb->posts
,$wpdb->posts
,"{$wpdb->prefix}soundcloud"
,$wpdb->posts.ID
,"{$wpdb->prefix}soundcloud.idpost"
,$wpdb->posts.post_type
,$wpdb->posts.post_name
,$name
), OBJECT );
echo \'<pre>\'.var_export( $all_posts, true ).\'</pre>\';
使用前缀
$wpdb;
提供
$wpdb->prefix
, 无论你在你的
wp-config.php
作为表前缀。然后附加表名:
{$wpdb->prefix}{$your_table_name}
或
"{$wpdb->prefix}soundcloud"
.