PDO 中的随机行计数

发布于 2024-09-11 03:51:06 字数 687 浏览 6 评论 0原文

我如何使用 PDO 获得随机行数?我仍在学习如何使用 PDO,所以这就是我尝试过的,但它不起作用,因为它没有随机化引号:

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

                 try {
                      $query = $this->_db->prepare($sql);
                      $query->execute();

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

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

我之前使用过这段代码,但没有 PDO 有效:

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

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 = $this->_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);**

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦屿孤独相伴 2024-09-18 03:51:06

如果您计划处理大量数据,我建议不要使用 ORDER BY Rand()。

有关解释/推理和替代方法,请参阅:Titov.Net - 不要使用 Order By RAND() 的文章。

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.

怎言笑 2024-09-18 03:51:06

您也可以使用 MySQL 执行此操作:

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

You could do this with MySQL as well:

$sql = "SELECT cQuotes, vAuthor, cArabic, vReference 
                              FROM thquotes 
                              ORDER BY RAND()
                              LIMIT 1";
多孤肩上扛 2024-09-18 03:51:06

要以随机顺序获取行,请添加 ORDER BY RAND()

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文