Remember Me
forgot your password?

PHP PDO MySQL:Simple Example Connecting to MySQL with PDO Class

I'll demonstrate a simple example on how to connect to mysql using PHP's PDO class. Just some of the benefits of PDO is that it's fast and if you use the PDO::prepare() method it will prevent SQL injection attacks by calling the PDO::quote() method. The other pros is that there are several databases it will support. So let's dive right into the code:

$hostname = 'localhost';
$username = 'your_username';
$password = 'your_password';

try {
$db = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
echo 'Connected to database';
}
catch(PDOException $e) {
echo $e->getMessage();
}

Fatal Error new PDO Instance

Just an important note that if you receive the following type of fatal error in your development environment:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000] [1049] Unknown database ''user''' in C:Program FilesApache Software FoundationApache2.2htdocstesttrunkcodelogin1classesstd.pdo_singleton.class.inc:30 Stack trace: #0 C:Program FilesApache Software FoundationApache2.2htdocstesttrunkcodelogin1classesstd.pdo_singleton.class.inc(30): PDO->__construct('mysql:host=loca...', 'username', 'password') #1 C:Program FilesApache Software FoundationApache2.2htdocstesttrunkcodelogin1classesstd.mysql.class_test.inc(43): db::getConnect() #2 C:Program FilesApache Software FoundationApache2.2htdocstesttrunkcodelogin1connect.php(6): MySqlDb->confirmUserPass('usertest', 'passtest') #3 {main} thrown in C:Program FilesApache Software FoundationApache2.2htdocstesttrunkcodelogin1classesstd.pdo_singleton.class.inc on line 30

Looks pretty messy and hard to decipher. When trying to decipher error code I usually look at the first error which led me to see why it was reporting an "Unknown database" when it was existing. The extra quotes also gave me a hint as to the problem. So I concluded the problem resulted in the placement of extra quotes around the values of host and/or dbname. The following will generate the previous error:

$db = new PDO("mysql:host='localhost';dbname='mysql'", $username, $password);

So if you do not use variables then do not add the single quotes for the values of host and dbname. In other words, use the following code instead:

$db = new PDO("mysql:host=localhost;dbname=mysql", $username, $password);

This is a simple test to connect to your mysql database or any other support database. Just for your information if you wish to connect to PostgreSQL which is another popular and robust database use the following code in place of the line of instantiation:

$db = new PDO("pgsql:dbname=pdo;host=localhost", "username", "password" );

If you're in a development environment and wish to display your errors directly to the screen you can specify the errors displayed. You need to set your display_errors settings to 'on' in your php.ini file. So set your error attributes after instantiating the PDO class like so:

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

There are three types of error report settings for PDO::ATTR_ERRMODE:
PDO::ERRMODE_SILENT = error codes
PDO::ERRMODE_WARNING = E_WARNING
PDO::ERRMODE_EXCEPTION = Throw exceptions

Here's an example of implementing PDO::ATR_ERRMODE:

$hostname = 'localhost';
$username = 'your_username';
$password = 'your_password';

try {
$db = new PDO("mysql:host=$hostname;dbname=articles", $username, $password);

echo 'Connected to database'; // check for connection

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

$sql = 'Select * from tutorialref where id=1';
$result = $db->query($sql);
foreach ($result as $row) {
echo $row['id'] .' - '. $row['author'] . '
';
}

$db = null; // close the database connection

}
catch(PDOException $e) {
echo $e->getMessage();
}

Don't confuse this with the errors generated from the php setting of error_reporting. The errors from PDO::ATTR_ERRMODE apply to the sql query and its results. I'll dive into the error settings and the different outputs of the php.ini error_reporting settings and PDO::ATTR_ERRMODE report settings in a future article.

Victor Kimura

PHP Tutorial, tips, guides. Learn PHP programming. Victor Kimura
PHP Tutorial Please view the original article to properly view the code and step-by-step snapshots:PHP PDO MySQL Connect Example

Rate this Article: 0 / 5 stars - 0 vote(s)
Print Email Re-Publish

Add new Comment



Captcha
0
1. Ashvin Ranpariya (13:59, 31.07.2009)
Hi i am Ashvin Ranpariya.....

there is good example of connecting MySQL with PDO Class,
most of the beginers getting help from here

  • Latest Programming Articles
  • More from Victor Kimura

A reason to smile for All PHP Developers

By: Mahendra Sharma | 28/11/2009
The PHP developers have full right to smile today due to their choice of career as PHP programmers. This article is highlighting some key factors on how this language is bypassing all other in the website development world.

How to Solve the Registry Errors

By: janson | 27/11/2009
The Registry of Windows is the most important for the working of the computer system due to it stores valuable data which can cause serious loss in performance of the system. The registry files of Windows are set to save the configuration settings of Windows and they are spread around on the hard disk. To solve the errors of them was absolute a Herculean task.

Gravity Jack Software Studio is a new venture that is pushing the envelope in the mobile software development arena

By: Adam Chronister | 26/11/2009
Gravity Jack opened offices this month in Liberty Lake and is currently filing patents regarding a tightly-kept secret project that is expected to revolutionize the way people interact with mobile computing platforms such as Apple’s iPhone and Google’s Android.

PHP and Open Source, Keys to build complex but Affordable websites

By: Mahendra Sharma | 26/11/2009
Gone are the days when high tech programmers and high profile companies were required to be engaged to develop a complex system on web. Open Source and especially PHP developers have changed the scenario. Every other day you can find new software available as open source developed by PHP programmers. Essential thing is such software is available for free or at nominal cost.

Java Application development India

By: Rightway Solution | 25/11/2009
Java is most suitable for creating Enterprise Applications for its flexibility and control. JAVA is used to create wide range of application with an extensive functionality.

Understanding the Typical Structure of Software Testing Process

By: yogindernath | 25/11/2009
Understanding the Typical Structure of Software Testing Process

CRM Customisation

By: Manny de Sousa | 24/11/2009
Next Generation CRM platforms need to offer full customisation. With the number of flexible design tools and components for .net and other development platforms there are no excuses for CRM providers not to offer truly simple customisation tools that can be used by non IT minded individuals

Computer technology - How to make your computer work faster?

By: janson | 24/11/2009
Computer slows down over time due to every day use. It makes simple tasks start taking minutes or hours to finish. In order to make the computer work effectively and quickly, it is necessary for the computer users to do something to improve the performance of the computer.

Windbg Minidump Tutorial:Setting up & Reading Minidump Files

By: Victor Kimura | 07/07/2009 | Programming
Windgb Minidump tutorial to set up and read minidump files (.dmp). Setting Symbol File Path. Output of Windbg command. windbg.exe -z [file path to minidump file.dmp] -c !analyze -v.

Thunderbird Cannot Connect to Server-Download Email Problem

By: Victor Kimura | 07/07/2009 | Software
Thunderbird cannot connect to server problem. How to resolve the problem if you have trouble downloading email from the server and the hour glass figure keeps displaying. Could be related to a virus, or Norton attempting to scan the infected email or a process error of Thunderbird.

Javascript Validate Name Field

By: Victor Kimura | 07/07/2009 | Programming
Simple Javascript tutorial on validating a name field. Checks to see if there is a value in the name field with Javascript after the user submits a form.

PHP PDO MySQL:Simple Example Connecting to MySQL with PDO Class

By: Victor Kimura | 19/06/2009 | Programming
A simple example on how to connect to a MySQL database with PHP PDO class. Possible errors in coding using PDO and short discussion on PDO error handling from MySQL results.

AutoIt:Connect to Access Databases:mdb & accdb files

By: Victor Kimura | 15/06/2009 | Programming
AutoIt tutorial discussing how to connect to an Access 2007 and 2003 database. .mdb and .accdb file extensions connections are made. How to retrieve a single record and place a field's value into a variable.

IMAP Multiple Connections / Processes Problem:Site Down

By: Victor Kimura | 15/06/2009 | Networks
IMAP with multiple connections can cause problems and bring down your website. This could be due to multiple IMAP processes that linger. You need to kill these IMAP processes in the control panel.

Web Hosting Transfer Domain:Transferring Domain to Another Provider or Account

By: Victor Kimura | 11/06/2009 | Networks
How to transfer domains to another web hosting provider or to another web hosting account (with the same provider). Step-by-step instructions for transferring your domain safely.

Submit Your Articles Free: Signup
Article Categories




Use of this web site constitutes acceptance of the Terms Of Use and Privacy Policy | User published content is licensed under a Creative Commons License.
Copyright © 2005-2008 Free Articles by ArticlesBase.com, All rights reserved. (0.65, 1, w1)