(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
  $username = "user_id";
  $database = "user_id";
  $password = "p-word";
  $host     = "undcemmysql.mysql.database.azure.com";

  // Initializing MySQLi
  $conn     = mysqli_init( );

  // Creating an SSL connection
  mysqli_ssl_set( $conn, NULL, NULL, "DigiCertGlobalRootCA.crt.pem", NULL, NULL );

  // Opening a new connection to the MySQL server
  mysqli_real_connect( $conn, $host, $username, $password, $database, 3306 );

  // Connect to the database.
  if ( mysqli_connect_errno( ) )
    die( 'Failed to connect to MySQL: ' . mysqli_connect_error( ) );

  $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'];
  }

  // Close the database connection.
  $conn->close( );
 ?>
 </body></html>
                     




      If a woman tells you she’s twenty and looks sixteen, she’s twelve.    
      If she tells you she’s twenty-six and looks twenty-six, she’s damn near forty.    
      — Chris Rock