我需要从 MySQL 数据库随机填充 2x 用户名。
假设我的数据库中有 clinton
、sanders
和 trump
作为用户(抱歉我无法控制自己)。
我只想将两个用户随机输入到变量中。我读了太多的剧本,让自己非常困惑。
$result = mysqli_query($mdb, "SELECT user FROM `table`");
$row = mysqli_fetch_row(array_rand($result,2));
echo $row[0] . "\n";
echo $row[1] . "\n";
我实际上要 sleep 了,因为我的泰迪熊很孤独,所以明天早上我会回顾并回复答案。谢谢。
最佳答案
我认为你应该再次离开你的泰迪熊并直接使用此查询
$result = mysqli_query($mdb, "SELECT user FROM `table` ORDER BY RAND() LIMIT 0, 2");
这会自动为您提供数据库中的两个随机条目,您将不再需要使用array_rand()
关于评论中关于大基数影响的问题,经过研究,它会产生很大的影响。我发现对此的评论http://www.petefreitag.com/item/466.cfm这提供了更好的选择
If you have a table with many rows, you can make this query much faster. A simple SELECT * FROM table ORDER BY RAND() has to do a sort in memory- expensive. If you change the query to SELECT * FROM table WHERE RAND()>0.9 ORDER BY RAND() then you've reduced the overhead of the sort by 90%. This will have the overhead of many RAND() statements, but on DB2 mainframes, it is a much faster technique.
关于php - 无法吐出 mysqli 随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36550186/