0

我试图从一个有 16k 行的表中获取 10 个结果。

此表中有一行称为视图,每次查看艺术家时都会获得 +1。但我得到意想不到的结果只有顶级艺术家。我为速度索引了视图行。我知道我必须循环它,但我不确定如何获取所有 10 行

我没有处理循环或一次获取多于一行的问题,需要帮助使用新的 mysqli 对其进行格式化

此处的示例返回数组的打印输出

// Get Top Viewed Artist
$TopViewedArtist = mysql_query("SELECT * FROM  `artists` ORDER BY  `artists`.`views` DESC LIMIT 10");
$TopViewedArtistInfo = mysql_fetch_assoc($TopViewedArtist);
$TopViewedArtist_TotalRows = mysql_num_rows($TopViewedArtist);
print_r($TopViewedArtistInfo); // the data returned from the query

这是以可读格式显示艺术家姓名结果的解决方案。

    $TopViewedArtists = mysql_query('SELECT * FROM `artists` ORDER BY `artists`.`views` DESC LIMIT 10');
    while (($TopArtist = mysql_fetch_assoc($TopViewedArtists)) !== FALSE) {
    //print_r($TopArtist);
    echo $TopArtist['artist']; echo "<br>";
    }

此代码可以为其他人更改。但需要更新到mysqli

4

2 回答 2

3

mysql_query返回一个result资源对象。把它想象成一个数组。读取该数组内容的唯一方法是遍历它。与数组mysql_fetch_assoc相同each:它返回下一行并递增内部指针。我认为这是你想要做的:

<?php
// Get Top Viewed Artist
$TopViewedArtists = mysql_query('SELECT * FROM `artists` ORDER BY `artists`.`views` DESC LIMIT 10');
while (($artist = mysql_fetch_assoc($TopViewedArtists)) !== FALSE) {
  print_r($artist);
}
?>

还要记住,它mysql_fetch_assoc返回一个包含多个值的数组。该数组应该包含您看到的所有内容;$artist['artist']使用(输出)访问值Gwen Stefani

May I suggest that you look into mysqli or PDO instead of the basic mysql functions? The only reason to use mysql_ functions is if you're stuck with PHP 4 (no longer supported so nobody should still be using it) or old applications. This looks like neither, and as it also seems you have no existing experience with the interface you really ought to look into the better options.

于 2012-11-09T01:40:36.897 回答
0

Basically, you want something like this:

$q=mysql_query("SELECT * FROM  `artists` ORDER BY  `artists`.`views` DESC LIMIT 10");
while($r=mysql_fetch_array($q)){//this will loop 10 times presuming there are at least 10 entries in your table
  //use $r here, it represents a single row
  print_r($r);
}

As other people have said, you should use mysqli or pdo and not the mysql_ functions

于 2012-11-09T01:41:00.293 回答