我有一个自定义表,用于存储引号和作者:
function quote_install(){
global $wpdb;
global $quote_db_version;
$table_name = $wpdb->prefix . \'quote\';
// create sql your table
$sql = "CREATE TABLE " . $table_name . " (
ID int(11) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT \'0000-00-00 00:00:00\' NOT NULL,
quote text NOT NULL,
author text NOT NULL,
qtag ENUM(\'G\', \'W\', \'Z\', \'H\', \'M\') NOT NULL default \'G\',
PRIMARY KEY (ID)
);";
require_once(ABSPATH . \'wp-admin/includes/upgrade.php\');
dbDelta($sql); }
然后,我想获得要显示的带有引号和作者的单行。
function read_single_Quote( $id=NULL ) {
global $wpdb;
$table_name = $wpdb->prefix . \'quotes\';
// random select
if($id ==NULL){
$sql = $wpdb->prepare( "
SELECT *
FROM {$wpdb->prefix}\'quotes\'
ORDER BY RAND()
LIMIT 1
");
} //get the row id = $id
else {
$sql = $wpdb->prepare( "
SELECT *
FROM {$wpdb->prefix}\'quotes\'
WHERE ID = %d
LIMIT 1
", $id );
}
$result = $wpdb->get_results( $sql );
// databse error, return false
if ( ! $result ) { return false; }
// return first result
return $result[0];
}
怎么了?从自定义表中获取随机行的最有效方法是什么?
SO网友:Paul \'Sparrow Hawk\' Biron
[注:@marwyk87在我写这篇文章时发布了他的答案,这代表了解决问题的另一种方法]
由于引用表名的方式,SQL中出现了一个简单的语法错误。你应该说
$sql = $wpdb->prepare( "
SELECT *
FROM {$wpdb->prefix}quotes
ORDER BY RAND()
LIMIT 1
");
以及
$sql = $wpdb->prepare( "
SELECT *
FROM {$wpdb->prefix}quotes
WHERE ID = %d
LIMIT 1
", $id );