PDO is PHP Data Objects which is used to connect to any database. Benefit of using PDO is that if there is any problem in our query it has an exception class to handle it. If any exception thrown to the try block, the script stops and directly flows to catch block. To make connection using PDO we are giving an example below:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "demol";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to create table
$sql = "CREATE TABLE employees (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "Table employees created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
The above program will create a table employees with field id,firstname,lastname,email and reg_date in the demo database. You will get the message Table employees created successfully on success.
0 Comment(s)