Array Rand 不适用于 MySQL Fetch Array


Array Rand Not Working with MySQL Fetch Array

我写了一个从MySQL查询中检索值的PHP脚本。我使用mysql_fetch_array将结果添加到数组中。我正在尝试从数组中选择一个随机值,但是array_rand似乎不起作用。我的代码如下:

<?php 
session_start();
ob_start();
require_once 'includes/db_connection.php';
require_once 'includes/contest.php';
require_once 'includes/survey.php';
require_once 'includes/poll.php';
require_once 'includes/clients.php';
require_once 'includes/user.php';
//Select All Entries from Contest and Save as Array
//Select 
mysql_connect(localhost,s2ktest_s2kuser, Bc33iyZYQWgUmguBehPI);
$dbname = 's2ktest_s2k';
mysql_select_db($dbname);
$contestid = 20;
$query = "SELECT UserID FROM Contest_Entered WHERE ContestID = $contestid";
//Save Result
$result = mysql_query($query) or die(mysql_error());
//Save All Contest Entries in Array
$entries = mysql_fetch_array($result) or die(mysql_error());
//Output all Rows
//While Each Entry in the Array is a Value
while($entries = mysql_fetch_array($result))
{
echo $entries;
echo "</br>";
}
echo array_rand($entries);
//mysql_free_result($result);
?>

也许是因为你没有任何数组...while 一次只生成一行。

while($entries = mysql_fetch_array($result))
 {
  echo $entries;
  $arr[] = $entries;
  echo "</br>";
 }
 echo array_rand($arr);
mysql_fetch_array()一次

只检索一行。 首先,使用 [] 追加语法将整个结果集加载到数组中,然后从中随机获取。

$all_entries = array();
// Using MYSQL_NUM to retrieve only numeric keys
// by default, mysql_fetch_array() gets both numeric and associative keys
while($entries = mysql_fetch_array($result, MYSQL_NUM))
{
  // Append all rows onto an array, only a sinlge value so you get a 1D array 
  $all_entries[] = $entries[0];
}
// Then call array_rand() against $all_entries
echo array_rand($all_entries);

免責聲明:

开始考虑从旧的mysql_*()函数迁移到支持预准备语句的现代 API。 PDO在RDBMS之间非常出色且可移植,而MySQLi也是一个很好的选择。

这是因为在启动循环时,$entries的值从数组更改为字符串。尝试在循环之前回显array_rand($entries)

但是,如果您尝试从表中检索随机行(而不是像代码那样从行中检索随机列),请在查询中使用ORDER BY RAND()。目前还不清楚你要做什么。

祝你好运!