开发者

random rowcount in PDO

how would i get a random rowcount using PDO? i'm still learning how to use PDO so this is what i tried, but it didn't work because it doesn't randomize the quotes:

$sql = "SELECT COUNT(*) AS rows FROM thquotes;";

                 try {
                      $query = $thi开发者_如何学运维s->_db->prepare($sql);
                      $query->execute();

                      **$rowcount = $query->rowCount();
                      $rand = rand(0,$rowcount-1);**

                      $sql = "SELECT cQuotes, vAuthor, cArabic, vReference 
                              FROM thquotes 
                              LIMIT $rand, 1";

i was using this code earlier without PDO which worked:

**$rowcount = mysql_result($result, 0, 0);
$rand = rand(0,$rowcount-1);**


If you are planning on working with large amounts of data, I would suggest against using ORDER BY Rand().

For the explanation / reasoning and an alternative method see: Titov.Net - Do not use Order By RAND()'s article.


You could do this with MySQL as well:

$sql = "SELECT cQuotes, vAuthor, cArabic, vReference 
                              FROM thquotes 
                              ORDER BY RAND()
                              LIMIT 1";


To get the lines in a random order, add ORDER BY RAND().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜