In this tutorial how to insert data in a MySQL table using PDO Method in PHP
MySQL INSERT Query using PDO Method
We will discuss PHP PDO Method. Example is given below.
//Database connection try{ $pdo = new PDO("mysql:host=localhost;dbname=domaincom_member", "database user", "database Password"); // Set the PDO error mode to exception $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e){ die("ERROR: Could not connect. " . $e->getMessage()); } // insert query execution try{ $sql = "INSERT INTO member (name,addr,email) VALUES ('saurav', 'kolkata', '[email protected]')"; $pdo->exec($sql); echo "Records inserted successfully."; } catch(PDOException $e){ die("ERROR: Could not able to execute $sql. " . $e->getMessage()); } // Close connection unset($pdo); ?>
This new PDO() function is establish database connection. Next set POD error mode. $e variable show database connecting error. INSERT INTO sql query insert data Mysql database table. $pdo->exec($sql) function executed INSERT INTO sql query. Then close connection.
Database Structure example is given below
PDO Handle Errors
The three type error modes manage the error mode attribute in your newly created database connection.
- PDO::ERRMODE_SILENT
- PDO::ERRMODE_WARNING
- PDO::ERRMODE_EXCEPTION
Example is given below
$pod->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT ); $pod->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING ); $pod->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
Three methods are writing in the INSERT INTO statement. Procedural Method and Object Oriented Method as we discussed earlier.