PHP MySQL Insert Query

In the previous example, you've understood how to create a database and tables in MySQL. In this tutorial, you will learn how to execute the SQL query to insert records into a table.

PHP MySQL Insert Query

Here is a PHP script that inserts records into the database table in the MySQL server:

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$host= "localhost";
$username= "root";
$password = "";

$db_name = "demo_db";

$mysql_connection = mysqli_connect($host, $username, $password, $db_name);
 
// Check connection
if ($mysql_connection->connect_errno) {
    printf("connection failed: %s\n", $mysql_connection->connect_error());
    exit();
}
 
//Create SQL insert query and store in a variable
$sql = "INSERT INTO students (first_name, last_name, email) VALUES ('john', 'cena', 'cena@mail.com')";

if(mysqli_query($mysql_connection, $sql)){
    echo "Records inserted successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($mysql_connection);
}

//Create SQL insert query and store in a variable
$sqlSecond = "INSERT INTO students (first_name, last_name, email) VALUES ('tony', 'stark', 'tony@mail.com')";

if(mysqli_query($mysql_connection, $sqlSecond)){
    echo "Records inserted successfully.";
} else{
    echo "ERROR: Could not able to execute $sqlSecond. " . mysqli_error($mysql_connection);
}

// Close connection
mysqli_close($mysql_connection);
?>
Let's understand the above PHP script.

The mysqli_connect() function opens a new connection to the MySQL server:
$host= "localhost";
$username= "root";
$password = "";

$db_name = "demo_db";

$mysql_connection = mysqli_connect($host, $username, $password, $db_name);

SQL query for inserting data into a database table:

//Create SQL insert query and store in a variable
$sql = "INSERT INTO students (first_name, last_name, email) VALUES ('john', 'cena', 'cena@mail.com')";

The mysqli_query() function performs a query against a database:

if(mysqli_query($mysql_connection, $sql)){
    echo "Records inserted successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($mysql_connection);
}

Closing MySQL server connection:

// Close connection
mysqli_close($mysql_connection);

Comments