行s> 0时PHP sql

What im trying to do here is generate a random number. Now i want to validate if the randomnumber exists in the database and if it existed it should generate another random number and validate it again. I tried using if (mysql_num_rows>0) but its not the right way.
Someone pls help me on this. Thanks!

PHP CODE:

  $randomnumber= rand(1000,9999);
  $sql = "SELECT * FROM table WHERE column= '$randomnumber'";
  $result = mysql_query($sql) or die(mysql_error());
  $numrows = mysql_num_rows($result);
  //while loop

WHAT I DID:

$randomnumber= rand(1000,9999);
$sql = "SELECT * FROM table WHERE column= '$randomnumber'";
$result = mysql_query($sql) or die(mysql_error());
$numrows = mysql_num_rows($result);
if ($numrows>0)
{
$randomnumber =rand(1000,9999);
$sql = "SELECT * FROM table WHERE column= '$randomnumber'";
$result = mysql_query($sql) or die(mysql_error());
}

$generated = false;

while($generated == false)
{
    $randomnumber= rand(1000,9999);
    $sql = "SELECT column FROM table WHERE column= '$randomnumber'";
    $result = mysql_query($sql) or die(mysql_error());
    $numrows = mysql_num_rows($result);

    if($numrows == 0)
    { 

        $sql_insert = "INSERT INTO table (column) VALUES ('". $randomnumber ."')";

        if($result = mysql_query($sql_insert))
        {
            $generated = true;
            echo 'Random number generated and inserted into table: ' . $randomnumber;
        }
    }
}

This script runs until a random number is not found. It then inserts it into the table if it does not exist. You can also run a version of this without the inserting if you already have a table filled with random numbers.

$found= false;

while($found== false)
{
    $randomnumber= rand(1000,9999);
    $sql = "SELECT column FROM table WHERE column= '$randomnumber'";
    $result = mysql_query($sql) or die(mysql_error());
    $numrows = mysql_num_rows($result);

    if($numrows >= 1)
    { 
        $found= true;
        echo 'Random number found in table! Random number matched was: ' . $randomnumber . '</br>';
    }else
    {
        echo 'No match for ' . $randomnumber . '</br>';
    }
}

I think, a better approach would be to fill the database will all possible random number values and set an is_free-flag. The others columns should be set to NULL.

And then you use a query with the RAND()-function:

SELECT id FROM table WHERE is_free = 1 ORDER BY RAND() LIMIT 1;

This method will always use only one run until all rows are used (is_free = 0).

Your current way may cause, that you have to run your code practical endless.