How to use PHP PDO to Insert Data Into a Table?

Learn, how to insert data into tables using PDO in PHP programming language?
Submitted by Bhanu Sharma, on September 25, 2019 [Last updated : March 13, 2023]

Inserting data is very simple as we already know how to establish connection with mysql (MariaDB) using PDO? We can use the same code as a skeleton and then edit the $sql query to insert data instead of selecting.

PHP code to insert data into table using PDO

<?php
//Connection Variables
$host = "localhost";
$uname = "username";
$pw = "password";
$db = "DBtest";

try {
    $conn = new PDO("mysql:host=$host;dbname=$db", $uname, $pw);

    // set error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // SQL insert query
    $sql = "INSERT INTO users (firstname, lastname, email)
    VALUES ('John', 'Abraham', '[email protected]')";

    // use exec() because no results are returned
    $conn->exec($sql);

    echo "New record created successfully";
}
catch(PDOException $e) {
    echo $sql . $e->getMessage();
}

//Set Connection state to null
$conn = null;

?>

Output

New record created successfully

This way, we can interact with MySQL using PDO to easily add new records to database table.

PHP Database Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.