进行一会儿/循环以获得10个随机结果 [英] Doing a while / loop to get 10 random results

查看:56
本文介绍了进行一会儿/循环以获得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次吗?例如,使用相同的回显,但打印出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>";
}

稍后修改 其他考虑因素将是:

Later edit Other considerations would be:

  • 如果表中包含大量数据(但似乎不会),那么按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天全站免登陆