MySQL Insert Data

PHP MySQL Insert Data

After a database and a table have been created, we can start adding data into them.

To add a new row of data, we use the SQL INSERT INTO statement.


The INSERT INTO Statement

The basic syntax looks like this: INSERT INTO table_name (column1, column2, column3) VALUES (value1, value2, value3)

Notice that we do not specify a value for the id or reg_date columns. Because we set them up with AUTO_INCREMENT and CURRENT_TIMESTAMP, MySQL handles them automatically!

Insert Data Example

<?php
$servername = "localhost";
$username = "root";
$password = "your_password";
$dbname = "myDB";

// Create connection $conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }

// Insert query $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); }

mysqli_close($conn); ?>


Exercise

?

Which SQL statement is used to add new rows of data into a MySQL table?