Search This Blog

Thursday, March 4, 2010

Random di PHP

A friend asked about the random function in PHP. coincidence this blog has not been updated. it altogether, update blogs and helped my friends. ok..let's play the listing ...:) :

echo rand() . "\n";
echo
rand() . "\n";

echo
rand(5, 15);
?>

result :
123
242
2

random in the query

// First get the last id from the table

$SQL = "SELECT * FROM HIGHLIGHTS ORDER BY highlight_id DESC LIMIT 1";
$result = mysql_query( $SQL );
while(
$row = mysql_fetch_array( $result ) ) {
$ending_id = $row["highlight_id"];
}

// I only want the 5 most recent entries
// So I just subtract 5 from the last ID

$starting_id = $ending_id - 5;

// Because I we don't want a nagitive number I just
// make sure that the starting ID is at least 1

if($starting_id <= 0){
$starting_id = "1";
}

// now I run the the $starting_id $ending_id at RAND

$howey = rand($starting_id, $ending_id);

// Now I use howey as my id

$SQL = "SELECT * FROM HIGHLIGHTS WHERE highlight_id = '$howey'";
$result = mysql_query( $SQL );
while(
$row = mysql_fetch_array( $result ) ) {
$highlight_id = $row["highlight_id"];
$highlight_title = $row["highlight_title"];
}
echo
"$highlight_id $highlight_title";
?>

to download the PHP random sample click here

Calendar