We are showing how to insert new record into MySQL database. We will explain both MySQLi and PDO approaches.
Let's start with MySQLi extension. Jump straight with an example. We are using OOP approach.
First of all we are establishing the connection with the database.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn-gt;connect_error) {
die("Connection failed: " . $conn-gt;connect_error);
}
Now, we are inserting a new record into table users. Just watch that string values are quoted and numeric values are not quoted. Finally, we are closing the connection.
$sql = "INSERT INTO users (firstname, lastname, age, email)
VALUES ('John', 'Doe', 35, 'john@example.com')";
if ($conn-gt;query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "lt;brgt;" . $conn-gt;error;
}
$conn-gt;close();
Now, we are going to add a new record using PDO approach.
First of all, we are creating database connection. Then we set PDO error mode to exception. We merge the entire code within try-catch block.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn-gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Now, we are inserting a new record by calling the exec() function and passed the SQL query into it as a parameter. Finally, we are closing the connection after completing all the tasks.
$sql = "INSERT INTO users (firstname, lastname, age, email)
VALUES ('John', 'Doe', 35, 'john@example.com')";
$conn-gt;exec($sql);
echo "New record created successfully";
} catch(PDOException $e) {
echo $sql . "lt;brgt;" . $e-gt;getMessage();
}
$conn = null;
On this page of the site you can watch the video online How to insert data into a database using PHP with a duration of hours minute second in good quality, which was uploaded by the user PHP Explained 24 April 2025, share the link with friends and acquaintances, this video has already been watched 145 times on youtube and it was liked by 1 viewers. Enjoy your viewing!