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;
Sur cette page du site, vous pouvez voir la vidéo en ligne How to insert data into a database using PHP durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur PHP Explained 24 avril 2025, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 145 fois et il a aimé 1 téléspectateurs. Bon visionnage!