做一段时间/循环以获得10个随机结果 [英] Doing a while / loop to get 10 random results

查看:22
本文介绍了做一段时间/循环以获得10个随机结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试为我的网站制作标签脚本,以便每次搜索引擎访问我的网站时,我的网站上都会显示 10 个不同的标签.

Hello i'm trying to make a tag script for my website so each time a search engine comes to my website 10 different tags will show on my website.

这些标签将从数据库中抓取.所以此刻我已经对其进行了编码,因此它只抓取了一个.(因为我不知道如何做 while )

These tags will be grabbed from the db. So at the minute i have coded it so it grabs only one. ( because i don't know how to do a while )

像这样

$sql = "SELECT tagname FROM tags ORDER BY rand() LIMIT 10";
$result = mysql_query($sql);
$row = mysql_fetch_object($result);
echo "<a href='index.php'>" .$row->tagname. " </a>";

无论如何我可以添加一段时间以便它执行 10 次吗?例如,使用相同的 echo 但打印出 10 个结果而不是 1 .... 我已将限制从 1 更改为 10 但这不起作用...仍然显示一个...

Is there anyway i can add a while to that so it does it 10 times ? E.g use the same echo but print out 10 results instead of the 1 .... i have changed the limit from 1 to 10 but that did not work... still showing one...

推荐答案

注意,在真正的答案之前阅读:对于那些不断反对这个答案的人.阅读标题(以做一段时间"开头)和最后一部分,问题(无论如何我可以添加一段时间,以便它做到这一点10倍 ?").这个答案是关于迭代结果集,而不是关于 RAND 函数的用法!该查询甚至没有出现在我的回答中,我还建议在最后采用不同的方法:

Note, read before the real answer: for the ones that keep downvoting this answer. Read the title (that starts with "Doing a while") and the final part, the question ("Is there anyway i can add a while to that so it does it 10 times ?"). This answer is about iterating the result set, not about the usage of the RAND function! The query doesn't even appear in my answer, and I am also suggesting a different approach at the end:

你只需要在一个循环中包装你对 mysql_fetch_object 的调用

you just need to wrap your call to mysql_fetch_object in a loop

$result = mysql_query($sql);

while ($row = mysql_fetch_object($result))
{
echo "<a href='index.php'>" .$row->tagname. " </a>";
}

稍后编辑其他考虑因素是:

  • 如果表包含大量数据(但似乎不会),按 rand() 排序会对性能产生不良影响
  • 考虑使用 pdo(或至少 mysqli)
  • 你应该有一些错误处理,即使查询似乎是完美,至少

  • if the table hold a very big amount of data (but it doesn't seem that it will) order by rand() can have a bad effect on the performance
  • consider using pdo (or at least mysqli)
  • you should have some error handling even if the query seems to be perfect, at least

如果 (!$result){回声 mysql_error();死;}

if (!$result) { echo mysql_error(); die; }

这篇关于做一段时间/循环以获得10个随机结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆