PHP MySQL tutorial

Inserting Data in MySQL Table via PHP Script

Until now, we have seen how to create a database and how to create a table within that database. Now is the time to insert some dummy data in the table we have created. Normally table data is populated when a user submits a form. The INSERT query is used for inserting data into the table. Syntax of insert query is as follows:

INSERT INTO table ( column1, column2, column3...columnK )
                       VALUES
                       ( value1, value2, value3, ...valueK );

The following example explains how to create a form that takes data from user in the text fields and inserts that data to the Patient table in the ‘Hospital’ database.




Patient Record Insertion



    



Download the code

The above code will generate a form that contains Patient First Name, Patient Last Name and Patient Age text fields. When user enters some values in these fields and press Enter Record button, POST request will be sent to “Php-insertdata.php” page where data insertion code is written. The data in the text fields will be inserted into corresponding columns of the Patient table of the Hospital database. The code for “Php-insertdata.php” is as follows:

connect_error) {
        die("Connection not established: " . $connection->connect_error);
    } 

    $query = "Use Hospital";
    $connection->query($query);

    // Insert Data
    $query = "INSERT INTO Patient ".
       "(patient_fname,patient_lname, patient_age) ".
       "VALUES ".
       "('$patient_fname','$patient_lname','$patient_age')";
    
    if ($connection->query($query) === TRUE) {
        echo "Record Inserted Successfully.";
    }
    else {
        echo "Unable to add record. " . $connection->error;
    }

    $connection->close();
    
?>

Download the code

This example uses object oriented MySQLi to insert data into PHP tablesThe above code is a very crude example of inserting data into MySQL tables. Actual data insertion involves field validation and null checks etc.

<<< Drop Table in MySQLSelecting MySQL Table Data via PHP Script >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .