You should move the check into the function. Then you can put a conditional in there that if it exists, try again, otherwise, return it
function RandomString($length=8) {
//Generate alphabet array
$alphabet = "";
for ($i = 0; $i < 26; $i++) {
@$alphabet .= chr(97+$i).",";
}
$alphabet = explode(",", $alphabet);
$RandomString = "";
//Check that length is between 1 and 40
if ($length > 40 || $length < 1) {
$length = 8;
}
//Generate Random string
for ($i = 1; $i <= $length; $i++) {
$rand = rand(0, 25);
$RandomString .= $alphabet[$rand];
}
$conexion=mysql_connect("","","");
mysql_select_db("database",$conexion);
$sql = mysql_query("SELECT * FROM Reservas WHERE codigo= '".$RandomString."'");
if (mysql_num_rows($sql) > 0) {
RandomString();
}
else {
return $RandomString;
}
}