Q:

PHP PDO Inserting data into tables

belongs to collection: PHP Database Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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', 'john@abraham.com')";

    // 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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Invoice Example... >>
<< PHP example to fetch data from MySQL (MariaDB) dat...