【问题标题】:MySQL. Random rows. Convert rows into PHP arrays.mysql。随机行。将行转换为 PHP 数组。
【发布时间】:2012-02-12 08:42:50
【问题描述】:

我有一个四列的 MySQL 表,submited_name, submited_URL, submited_type, uniqueID。在这张表中,我有大约 1000 条记录。我需要选择 10 个随机条目。问题是我需要将选定的随机值拆分为单独的 PHP 数组。每列一个。我的数组应该是这样的:

$ten_random_names = array ('name26', 'name55', 'name107', ect.);
$ten_random_URL = array ('url for name26', 'url for name55', 'url for name107', ect..);
$ten_random_types = array ('type for name26', 'type for name55', 'type for name107', ect..);

【问题讨论】:

标签: php mysql


【解决方案1】:

基础知识:

$sql = "SELECT name, url, type FROM ... WHERE ... ORDER BY random() LIMIT 10"; // inefficient, but works
$results = mysql_query($sql) or die(mysql_error());

$names = $url = $types = array();
while($row = mysql_fetch_assoc($results)) {
   $names[] = $row['name'];
   $url[] = $row['url'];
   $type[] = $row['type'];
}

【讨论】:

  • 你不应该在查询中添加LIMIT 10吗?
【解决方案2】:
$query = "SELECT *
          FROM tablename
          ORDER BY RAND()
          LIMIT 10";
$result = mysql_query($query);

$ten_random_names = $ten_random_URL = $ten_random_types = array();
while ($row = mysql_fetch_assoc($result)) {
  $ten_random_names[] = $row['submited_name'];
  $ten_random_URL[] = $row['submited_URL'];
  $ten_random_types[] = $row['submited_type'];
}

【讨论】:

  • mysql 扩展已过时,即将弃用。新代码应该使用 mysqli 或 PDO,两者都有重要的优势,比如支持prepared statements。
猜你喜欢
  • 2013-10-09
  • 2016-12-11
  • 1970-01-01
  • 2017-02-15
  • 1970-01-01
  • 2014-04-30
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
相关资源
最近更新 更多