PHP MySQL Order by Keyword


The ORDER BY keyword is used to sort the data in a recordset. It is possible to order by more than one column. When ordering by more than one column, the second column is only used if the values in the first column are identical. The following example creates and populates a Products table using the following SQL commands:

CREATE TABLE Products (
  ID   INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(16) NOT NULL );
 
INSERT INTO Products( name ) VALUES( '$name' );

and selects products using the ORDER BY operator:

SELECT * FROM Products ORDER BY ID, name;

           
 <html><body>
 <?php
  $servername = "undcsmysql.mysql.database.azure.com";
  $username   = "user.id@undcsmysql";
  $password   = "password";
  $dbname     = "user_id";         # your database or schema
  // Connect to the database.
  $conn       = new mysqli( $servername, $username, $password, $dbname );

  $table =  Drop    Create    Insert (name = "")          
    Select ( order by  ID  ASC  DESC,    name  ASC  DESC ) 
  if ( $action == "Drop" ) {
    // Drop table Products.
    $conn->query( "DROP TABLE Products" );
    echo "Table Products dropped";
  }
  elseif ( $action == "Create" ) {
    // Create table Products.
    $sql = "CREATE TABLE Products (
              ID   INT AUTO_INCREMENT PRIMARY KEY,
              name VARCHAR(16) NOT NULL )";
    $conn->query( $sql );
    echo "Table Products created";
  }
  elseif ( $action == "Insert" ) {
    // Insert product.
    $sql = "INSERT INTO Products( name ) VALUES( '$name1' )";
    $conn->query( $sql );
    echo " Prodoct $name1 entered"
  }
  elseif ( $action == "Select" ) {
    // Select products.
    if ( isset( $ID ) && isset( $name2 ) )
      $columns = $ID . " " . $order1 . ", " . $name2 . " " . $order2;
    elseif ( isset( $ID ) )
      $columns = $ID . " " . $order1 ;
    elseif ( isset( $name2 ) )
      $columns = $name2 . " " . $order2 ;

    $sql = "SELECT * FROM Products ORDER BY $columns";
    $result = $conn->query( $sql );
    while ( $row = $result->fetch_assoc( ) )
      echo $row['ID'] . ", " . $row['name'];
  }
  $conn->close( );
 ?>
 </body></html>




      How do you get two whales in a car?    
      Start in England and drive west.