# PHP script to connect to MySQL database using PDO

Introduction

I am preparing to use a basic script to cover how you can connect to a MySQL database using PDO. This script is meant for educational purposes (introductory class on PHP/MySQL) and does of course not cover all security aspects of database connections.

Points of focus

1. Conformity to the PSR-1 and PSR-2 standards.
2. Structure for connecting to database connection.
3. Security aspects that has not been covered.

Code (settings.php):

<?php
// Defines database connection information
$settings = [ 'host' => '127.0.0.1', 'name' => 'c9', 'port' => '3306', 'charset' => 'utf8', 'username' => 'admin', 'password' => 'root' ]; ?>  Code (db.php): <?php // Includes database connection information require_once('../settings.php'); // Establishes connection to database server try {$dbh = new PDO(
sprintf(
'mysql:host=%s;dbname=%s;port=%s;charset=%s',
$settings['host'],$settings['name'],
$settings['port'],$settings['charset']
),
$settings['username'],$settings['password']
);
// Prevents emulated prepare statements and sets error mode
// to PDO::ERRMODE_EXCEPTION
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
// Prints out errors raised by PDO
catch (PDOException $e) { die('Error: ' .$e->getMessage());
}
?>


The ../ for settings.php indicates that the file is outside document root for security purposes. Much appreciated in advance for any comments that could improve this code.

I don't use PHP often, but here are a few comments:

Use Objects to Manage Resources

Like any other language with object-oriented capabilities, PHP serves you best when you manage resources with objects. I'd strongly recommend holding your PDO object within a custom class that manages the connection. This makes the code easier to maintain and doesn't actually have to change much about what you did. The code will also be more extensible. Also, introducing OOP is a very good lesson for students starting out.***

You could then also show them lazy-loading, making sure the PDO isn't opened until there is actually communicating between the server and the database.