这个循环有更好的解决方案吗?

时间:2012-05-26 18:00:39

标签: php

我正在制作一个基本上显示随机图像的网站,但我现在需要更好的代码。我希望有人能提出更好的解决方案。

$p = $_GET["p"];
$qrynumrows = mysql_query("SELECT * FROM pictures");
$numrows = mysql_num_rows($qrynumrows);

if (!isset($p)) {
    $randid = rand(1, $numrows);
    $qryrecord = mysql_query("SELECT * FROM pictures WHERE id='$randid'");

    while ($row = mysql_fetch_array($qryrecord)) {
        $rowp = $row["p"];
        $rowremove = $row["remove"];
    }

    if ($rowremove == 1) {
        header("Location: http://www.lulzorg.com/");
        exit();
    }
    else {
        header("Location: http://www.lulzorg.com/?p=$rowp");
        exit();
    }       
}

所以它正在做的是从数据库中挑选一个随机记录,但它需要检查是否允许记录。代码的工作正常,但我确信有更好/更快的方法。

如果$ rowremove等于0,则允许显示图像。如果$ rowremove等于1,则不允许显示图像。

感谢。

3 个答案:

答案 0 :(得分:1)

ID不一定是连续的,因此您获取随机行的方式很可能会被破坏。

获得单个随机行的最简单方法是:

SELECT ... FROM ... WHERE remove = 0 ORDER BY rand() LIMIT 1

由于您只获得一行,因此无需循环:

$row = mysql_fetch_assoc($qryrecord);

然后只需使用$row['p'] $row != false

header("Location: http://www.lulzorg.com/?p='.$row['p']);
exit;

以下是您需要的完整代码:

$p = isset($_GET['p']) ? $_GET['p'] : 0;
if (!$p) {
    $qryrecord = mysql_query("SELECT * FROM pictures WHERE remove = 0 ORDER BY rand() LIMIT 1");

    $row = mysql_fetch_assoc($qryrecord);
    if(!$row) {
        // No valid row. Do something.
        exit;
    }
    header('Location: http://www.lulzorg.com/?p=' . $row['p']);
    exit;
}

答案 1 :(得分:1)

不是生成随机ID,而是在按RAND()排序结果后选择第一行。此外,检查行中的NOT remove(相当于remove = 0),以消除单独检查行的需要。

$p = $_GET["p"];

if (is_int($p))
{
    $qryrecord = mysql_fetch_row(mysql_query("SELECT p FROM pictures WHERE NOT remove ORDER BY RAND() LIMIT 1"));
    $rowp = $qryrecord[0];
    header("Location: http://www.lulzorg.com/?p=$rowp");
    exit();
}

答案 2 :(得分:0)

SELECT * FROM pictures WHERE id='$randid' AND rowremove == 0

有了这个,你的整个事情很容易被改写为:

$p = $_GET["p"];

if (!isset($p)) 
{
    $randid = rand(1, $numrows);
    $qryrecord = mysql_query("SELECT * FROM pictures WHERE id='$randid' AND rowremove == 0");
    $row = mysql_fetch_array($qryrecord);

    if($row)
    {
        $rowp = $row["p"];
        header("Location: http://www.lulzorg.com/?p=$rowp");
        exit();
    }
    header("Location: http://www.lulzorg.com/");
}
相关问题