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

I'm making a website which basically displays a random image but I need a better bit of code of what I have at the moment. I'm hoping someone could come up with a better solution.

$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();
    }       
}

So what it's doing is picking a random record from the database but it needs to check whether the record is allowed. The bit of code works fine but I'm sure there's a better/faster way to do it.

If $rowremove is equal to 0 then the image is allowed to display. If $rowremove is equal to 1 then the image is NOT allowed to display.

Thanks.

Instead of generating a random ID, just select the first row after ordering the results by RAND(). In addition, check for NOT remove (equivalent to remove = 0) in the rows to remove the need to check the rows individually.

$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();
}
SELECT * FROM pictures WHERE id='$randid' AND rowremove == 0

With that, your whole thing can easily be rewritten as:

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

IDs are not necessarily consecutive so your way to get a random row is most likely broken.

The easiest way to get a single random row is this:

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

Since you only get one row, there's no need for a loop:

$row = mysql_fetch_assoc($qryrecord);

And then simply use $row['p'] if $row != false:

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

Here's the whole code you need:

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