PHP PDO Inserting data into tables

PHP PDO Inserting data into tables

Embeddings information into tables: Here, we will figure out how to embed information into tables utilizing PDO in PHP programming language?

Embeddings information is exceptionally basic as we definitely realize how to build up an association with MySQL (MariaDB) utilizing PDO? We can utilize a similar code as a skeleton and afterwards alter the $sql question to embed information as opposed to choosing.

PHP code to embed information into table utilizing 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

Along these lines, we can connect with MySQL utilizing PDO to effortlessly add new records to the database table.

Recent Posts

error: Alert: Content is protected!!