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

Php 这个循环有更好的解决方案吗?,php,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("

我正在做一个网站,基本上显示一个随机的图像,但我需要一个更好的代码位,我现在有什么。我希望有人能想出更好的解决办法

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

谢谢

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/");
}

ID不一定是连续的,所以获取随机行的方法很可能被破坏

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

SELECT ... FROM ... WHERE remove = 0 ORDER BY rand() LIMIT 1
因为您只得到一行,所以不需要循环:

$row = mysql_fetch_assoc($qryrecord);
如果
$row!=错误

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;
}

不生成随机ID,只需在按
RAND()
对结果排序后选择第一行即可。此外,检查行中是否有
不删除
(相当于
删除=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();
}

为什么每次循环运行时都会覆盖$rowp和$rowremovep?当然这不是你想要的吗?那就不需要一个while循环了……我想你忘了扔掉
$randid
这个东西——你只是用一个更好的解决方案替换了它,而且它很可能已经坏了(见我回答中的注释)@ThiefMaster:谢谢,我注意到了。我复制了他的原始查询,但忘记删除第一个条件。您可能还需要修复
isset
检查以避免通知。谢谢,已修复。即使你也可以这么做——你似乎有足够的机会编辑别人的答案。