Fungsi Random PHP

Fungsi mengacak angka di pemrogaman PHP
int rand ( void )
int rand ( int $min , int $max )
Contoh :
<?php
echo rand() . "\n";
echo rand() . "\n";
echo rand(5, 15);
?>
Hasil Output nya :
7771
22264
11


Contoh 1 : Algoritma mengacak untuk database MySQL

 <?php
 $query = "SELECT `id` FROM [TABLE]";
 $result = mysql_query($query, $link);
 $num = mysql_num_rows($result);
 if ($num > 0) {
     // Array the ID's...
     $id_array = array();
     while ($row = mysql_fetch_assoc($result)) {
         $id_array []=$row["id"];
     }
     $query = "SELECT * FROM [TABLE] WHERE `id`=".$id_array[rand(0, (count($id_array)-1))];
     $result = mysql_query($query, $link);
     $row = mysql_fetch_assoc($result);
     // ...
 }
 ?>

Contoh 2 : Algoritma mengacak untuk database MySQL


 <?php
 // 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";
 ?>


Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: