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', '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
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
PHP code to insert data into table using PDO
Output
need an explanation for this answer? contact us directly to get an explanation for this answer