Last Updated: March 29, 2017
·
235
· oliverusselldev

PDO Database Connection

By default, PHP has PDO_SQLite driver installed. However, if you wish to work with other databases, you must first install the relevant driver.

In order to check what drivers are installed on your system, create a new PHP file and add the following code snippet to it:

<?php

print_r(PDO::getAvailableDrivers());

?>

Creating a Table With PDO

<?php

include_once 'connection.php';

try

{

     $database = new Connection();

     $db = $database->openConnection();

     // sql to create table

     $sql = "CREATE TABLE `Student` ( `ID` INT NOT NULL AUTO_INCREMENT , `name`VARCHAR(40) NOT NULL , `last_ame` VARCHAR(40) NOT NULL , `email` VARCHAR(40)NOT NULL , PRIMARY KEY (`ID`)) ";

     // use exec() because no results are returned

     $db->exec($sql);

     echo "Table Student created successfully";

     $database->closeConnection();

}

catch (PDOException $e)

{

    echo "There is some problem in connection: " . $e->getMessage();

}

?>

Source: https://www.cloudways.com/blog/introduction-php-data-objects/