Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP MySQL Insert Data

PHP MySQL Insert Data


Insert Data into MySQL Using MySQLi and PDO

After creating the database and table, we can add data to the table.

Here are some syntax rules:

The INSERT INTO statement is usually used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)

VALUES (value1, value2, value3,...)

To learn more about SQL, please see our SQL tutorial.

In the previous chapters we have created the table "MyGuests" with fields: "id", "firstname", "lastname", "email", and "reg_date". Now, let's start filling the table with data.

Note Note: If a column is set to AUTO_INCREMENT (such as the "id" column) or TIMESTAMP (such as the "reg_date" column), we do not need to specify a value in the SQL query statement; MySQL will automatically add a value for that column.

The following example adds a new record to the "MyGuests" table:

Example (MySQLi - Object-Oriented)

connect_error ) { die ( " Connection failed: " . $conn -> connect_error ) ; } $sql = " INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com') " ; if ( $conn -> query ( $sql ) === TRUE ) { echo " new record inserted successfully " ; } else { echo " Error: " . $sql . "
" . $conn -> error ; } $conn -> close ( ) ; ?>

Example (MySQLi - Procedural)

" . mysqli_error ( $conn ) ; } mysqli_close ( $conn ) ; ?>

Example (PDO)

setAttribute ( PDO :: ATTR_ERRMODE , PDO :: ERRMODE_EXCEPTION ) ; $sql = " INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com') " ; // use exec(), no result returned $conn -> exec ( $sql ) ; echo " new record inserted successfully " ; } catch ( PDOException $e ) { echo $sql . "
" . $e -> getMessage ( ) ; } $conn = null ; ?>