PHP MySQL Create and Drop Tables (Cont.)


Each table should have a primary key field, which is used to uniquely identify the rows in a table. The primary key field cannot be null because the database engine requires a value to locate the record. The following example creates, populates, and selects a table Papers by using the SQL commands:

CREATE TABLE Papers (
  paperID INT NOT NULL AUTO_INCREMENT,
  title   VARCHAR(32) NOT NULL,
  PRIMARY KEY( paperID ) );
   
INSERT INTO Papers( title ) VALUES( '$title' );
SELECT * FROM Papers;

The primary key field is often an ID number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT automatically increases the value of the field by 1 each time a new record is added.

           
 <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 );

  $action =  Drop    Create    Insert ( $title = "" ) 
  if ( $action == "Drop" ) {       
    // Drop table Papers.
    $conn->query( "DROP TABLE Papers" );
    echo "Table Papers dropped";
  }
  elseif ( $action == "Create" ) {
    // Create table Papers.
    $sql = "CREATE TABLE Papers (
              paperID INT NOT NULL AUTO_INCREMENT,
              title   VARCHAR(32) NOT NULL,
              PRIMARY KEY( paperID ) )";
    $conn->query( $sql );
    echo "Table Papers created";
  }
  elseif ( $action == "Insert" ) {
    // Insert paper.
    $sql = "INSERT INTO Papers( title ) VALUES( '$title' )";
    $conn->query( $sql );

    // Select all papers.
    $result = $conn->query( "SELECT * FROM Papers" );
    while ( $row = $result->fetch_assoc( ) )
      echo $row['paperID'] . ", " . $row['title'];
  }
  $conn->close( );
 ?>
 </body></html>