Home » PHP » PHP Examples

PHP PDO Inserting data into tables

Inserting data into tables: Here, we are going to learn how to insert data into tables using PDO in PHP programming language?
Submitted by Bhanu Sharma, on September 25, 2019

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.