在MySQL數據庫中,如果想要得到一張表中隨機的Mysql數據,應該如何實現呢?下面就教您一個隨機獲取MySQL數據的方法,供您參考。
- header("Content-type:text/Html;charset=utf-8");
- $MySQL_host = 'localhost';
- $MySQL_un = 'root';
- $MySQL_pwd = '123456';
- $my_db_name = 'mytestdb';
- $my_table_name = 'mytesttable';
- $output_str = '';
- $resource = MySQL_connect($mysql_host,$mysql_un,$mysql_pwd) or dIE('MySQL connect error!');
- MySQL_select_db($my_db_name,$resource);
- $result = MySQL_query("select id from $my_table_name",$resource) or dIE('select data error');
- $my_id_array = array();
- while($row = MySQL_fetch_assoc($result)){
- if(is_numeric($row['id'])){
- $my_id_array[] = $row['id'];
- }
- }
- MySQL_free_result($result);
- if(count($my_id_array)>0){
- $rand_query_id = array_rand($my_id_array,1);
- $result = MySQL_query("select * from $my_table_name where id = $rand_query_id",$resource) or dIE('select data error2');
- $row = MySQL_fetch_assoc($result);
- $output_str = "{$row['foodname']}{$row['price']}{$row['tel']}";
- MySQL_free_result($result);
- }else{
- $output_str = 'Without any data';
- }
- MySQL_close($resource);
- echo $output_str;
- ?>
以上就是隨機獲取MySQL數據的方法的介紹。