note 32226 modified in function.mysql-data-seek by didou

From: Date: Tue, 20 May 2003 23:40:32 +0000
Subject: note 32226 modified in function.mysql-data-seek by didou
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-48700@lists.php.net to get a copy of this message
[EDITOR'S NOTE or just use SELECT SELECT temperature, drink FROM drinks ORDER BY RAND() LIMIT 1; the returned result set will contain a random choosen row from your bar ;) didou] Here is a nice little snippet to return a random row of a result set: <?php // suppose you have a database table of drinks :) // get the data $link = mysql_connect('localhost', 'mysql_user', 'mysql_password') or die('Could not connect: ' . mysql_error()); mysql_select_db('my_database') or die('Could not select database: ' . mysql_error()); $query = 'SELECT temperature, drink FROM drinks'; $result = mysql_query($query) or die('Query failed: ' . mysql_error()); // make sure you have at least one row if (mysql_num_rows($result) > 0) { // fetch one random row mysql_data_seek($result, rand(0, mysql_num_rows($result) - 1)); $row = mysql_fetch_object($result); // output your suggestion print 'you should now have a '.$row->temperature.' glass of '.$row->drink; // advertise for more print 'hit refresh when you are done'; } else { print 'sorry, no drinks in database!'; } ?> --was-- Here is a nice little snippet to return a random row of a result set: <?php // suppose you have a database table of drinks :) // get the data $link = mysql_connect('localhost', 'mysql_user', 'mysql_password') or die('Could not connect: ' . mysql_error()); mysql_select_db('my_database') or die('Could not select database: ' . mysql_error()); $query = 'SELECT temperature, drink FROM drinks'; $result = mysql_query($query) or die('Query failed: ' . mysql_error()); // make sure you have at least one row if (mysql_num_rows($result) > 0) { // fetch one random row mysql_data_seek($result, rand(0, mysql_num_rows($result) - 1)); $row = mysql_fetch_object($result); // output your suggestion print 'you should now have a '.$row->temperature.' glass of '.$row->drink; // advertise for more print 'hit refresh when you are done'; } else { print 'sorry, no drinks in database!'; } ?> http://www.php.net/manual/en/function.mysql-data-seek.php

« previous php.notes (#48700) next »