SQL PHP HTML ASP JavaScript articles and free scripts to download
PHP PDO

PHP MySQL connection using PDO

Before using database we need to connect it first. This process is common in all types of database irrespective of language we use. We will learn here the code for connecting to MySQL database using PDO class.

It is always a good practice to keep the database connection details at a common place and call it from different pages where it is required. This helps in maintaining the code when the database connection details changes or the script is shifted to different server with different connection details. If we are not using a common file then to change the database details we need not change the connection string in all the files. By keeping all details at one place if we update the details then all the files will use the same ( updated ) details.

We can keep the connection details in config.php file or any other file name you find suitable. All the codes inside this file are to be within the PHP code block, so it will not be exposed if it is opened directly in browser.

Let us start with the basic connection code in PDO for PHP & MySQL ( PHP MySQL Connection code for old system is here )

The code below is kept inside config.php file and can be connected from any other file in the script.

<?php
$host_name = "localhost";
$database = "pdo"; // Change your database name
$username = "root"; // Your database user id
$password = "test"; // Your password

//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host='.$host_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>

To get the database connection we have to keep these two lines inside any file and start using the database

require "config.php";

Be the first to post comment on this article :


Google+
Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked



HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2014 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer