0

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

$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,则不允许显示图像。

谢谢。

4

3 回答 3

1

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

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

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

由于您只得到一行,因此不需要循环:

$row = mysql_fetch_assoc($qryrecord);

然后简单地使用$row['p']if $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;
}
于 2012-05-26T18:06:15.970 回答
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();
}
于 2012-05-26T18:06:39.567 回答
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/");
}
于 2012-05-26T18:03:02.290 回答