Mengambil Nilai Random pada tabel database

kadang kita ingin mengambil nilai random dari table database, ini adalah cheat nya:


Buat dulu table nya

CREATE TABLE `lucky_cookies` (
`id` int(3) NOT NULL auto_increment,
`kata` text NOT NULL,
`org` varchar(100) default NULL,
PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;


masukan nilai ke dalam table:

INSERT INTO `lucky_cookies` (`id`, `kata`, `org`) VALUES
(1, ‘kata2 sok bijak’, ‘saya’),
(2, ‘i dont remember’, ”),
(3, ‘please forgive me, can’t stop loving u’, ‘bryan adams’),
(4, ‘the bully’, ‘sia’),
(5, ‘how u felling’, ”),
(6, ‘high and dry’, ‘audioslave’),
(7, ‘u turn to the lonely’, ‘sia’),
(8, ‘what and next’, ‘iam’),
(9, ‘leave me the high some’, ‘close’),
(10, ‘just losser, wich can’t fight’, ‘unbeat-able’);


lalu buat file PHP nya:

<?php
include(“../config/connect.php”);

$s = $_SERVER[PHP_SELF];

$l =  3;

$result = mysql_query(“SELECT * FROM lucky_cookies ORDER BY Rand() LIMIT $l”);

while($r = mysql_fetch_array($result)){
echo $r[id] . ” – ” . $r[kata] . “<br />”;
}
?>


hasilnya:

hasil_random_table

Published by

G3n1k

just to remember what i had known :)

One thought on “Mengambil Nilai Random pada tabel database”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s