我希望从同一条记录中随机检索一对列。不过,我听说 Rand 效率很低,所以我想使用不同的方式。 (很多文章都这么说,包括http://akinas.com/pages/en/blog/mysql_random_row/).
是的,我的标题几乎说明了一切。
例子:
记录:
12、詹姆斯、单簧管、鸡
16、比利、鼓、培根
15、Shane、吉他、披萨
系统会随机选择一条记录。那么就会
echo '一个名叫 $firstname 的男孩喜欢 $favoritefood'。
类似的事情。帮助?
有关 SQL 注入的标准免责声明。这应该可行,但我没有尝试:
// Get the number of rows in the table
$count = mysql_fetch_assoc(mysql_query('SELECT COUNT(`id`) AS `count` FROM `table`'));
// Use those to generate a random number
$rand = rand(1,$count['count']);
// Select the two columns we need, and use limit to set the boundaries
$query = 'SELECT `firstName`, `favoriteFood` FROM `table` LIMIT '.$rand.',1';
// Run the query
if(($result = mysql_query($query)) !== FALSE) {
// Dump the result into two variables
list($firstname, $favoritefood) = mysql_fetch_assoc($result);
// Echo out the result
echo 'A boy named '.$firstname.' likes '.$favoritefood;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)