PHP MySQL Update


The UPDATE statement is used to modify data in a database table. The following example creates and populates an Items table using the following SQL commands:

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

and updates the item using:

UPDATE Items SET name='$name2' WHERE ID=$ID;

           
 <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 ( name = "" )  
             Update ( SET name = "" WHERE ID = "")   
  if ( $action == "Drop" ) {
    // Drop table Items.
    $conn->query( "DROP TABLE Items" );
    echo "Table Items dropped";
  }
  elseif ( $action == "Create" ) {
    // Create table Items.
    $sql = "CREATE TABLE Items (
              ID   INT AUTO_INCREMENT PRIMARY KEY,
              name VARCHAR(16) NOT NULL )";
    $conn->query( $sql );
    echo "Table Items created";
  }
  elseif ( $action == "Insert" ) {
    // Insert item.
    $sql = "INSERT INTO Items( name ) VALUES( '$name1' )";
    $conn->query( $sql );
    echo "Item $name1 entered"
 
    // Select all.
    $result = $conn->query( "SELECT * FROM Items" );
    while ( $row = $result->fetch_assoc( ) )
      echo $row['ID'] . ", " . $row['name'];
  }
  elseif ( $action == "Update" ) {
    // Update item.
    $sql = "UPDATE Items SET name='$name2' WHERE ID=$ID";
    $conn->query( $sql );

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