Phone
07506 830432
info@digital75.co.uk
Address
6 Sunningdale Road, Macclesfield, Cheshire, SK11 8LU
In this tutorial I will show you how to connect to a MySQL database using the pdo method. The reason that we use the pdo method above other methods, such as MySQL and MySQLI, is the use of the prepared statements which have far superior security than the previously mentioned. Before continuing any further, you must already have a database set up and ready to use, if you don’t no how to create the database then follow the tutorial on creating mysql databases.
First, to find out what databases are supported on your server, add this code to a file
print_r(PDO::getAvailableDrivers());
To connect to a mysql database you simply need to create a new pdo object and supply it with the database details.
//Database Credentials
$host = 'localhost';
$database = 'DatabaseName';
$username = 'DatabaseUsername';
$password = 'DatabasePassword';
try {
$db = new PDO("mysql:host=$host;dbname=$database", $username, $password);
}
catch(PDOException $ex) {
echo $ex->getMessage();
}
echo "Database Connected";
To make the above sample work, all you need to do is fill in your database host, database username, database password and database name. If it connects to the database correctly it will display the message Database Connected, if there is an error connecting to the database then the pdo object will display an error and help you find the error.
The most common errors that people make, are: