如何通过使用其中的ORDER BY子句对MySQL表的数据进行排序来编写PHP脚本?

我们可以在PHP函数mysql_query()中使用类似ORDER BY子句的语法。该函数用于执行SQL命令,稍后再执行另一个PHP函数– mysql_fetch_array()可用于获取所有选定的数据。

为了说明这一点,我们有以下示例-

示例

在此示例中,我们正在编写一个PHP脚本,该脚本将按教程作者的降序返回结果-

<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
   $sql = 'SELECT tutorial_id, tutorial_title,
      tutorial_author, submission_date
      FROM tutorials_tbl
      ORDER BY tutorial_author DESC';

   mysql_select_db('TUTORIALS');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not get data: ' . mysql_error());
   }

   while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
      echo "Tutorial ID :{$row['tutorial_id']} <br> ".
         "Title: {$row['tutorial_title']} <br> ".
         "Author: {$row['tutorial_author']} <br> ".
         "Submission Date : {$row['submission_date']} <br> ".
         "--------------------------------<br>";
      }
   echo "Fetched data successfully\n";
   mysql_close($conn);
?>
猜你喜欢