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

Reference | in ,,, | by Victor Kimura

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:n$hostname = ‘localhost’;n$username = ‘your_username’;n$password = ‘your_password’;ntry {n$db = new PDO(“mysql:host=$hostname;dbname=mysql”, $username, $password);necho ‘Connected to database’;n}ncatch(PDOException $e) {necho $e->getMessage();n}nFatal Error new PDO InstancenJust an important note that if you receive the following type of fatal error in your development environment:nFatal 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 30nLooks 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:n$db = new PDO(“mysql:host=’localhost’;dbname=’mysql’”, $username, $password);nSo 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:n$db = new PDO(“mysql:host=localhost;dbname=mysql”, $username, $password);nThis 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:n$db = new PDO(“pgsql:dbname=pdo;host=localhost”, “username”, “password” );nIf 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:n$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);nThere are three types of error report settings for PDO::ATTR_ERRMODE:nPDO::ERRMODE_SILENT = error codesnPDO::ERRMODE_WARNING = E_WARNINGnPDO::ERRMODE_EXCEPTION = Throw exceptionsnHere’s an example of implementing PDO::ATR_ERRMODE:n$hostname = ‘localhost’;n$username = ‘your_username’;n$password = ‘your_password’;ntry {n$db = new PDO(“mysql:host=$hostname;dbname=articles”, $username, $password);necho ‘Connected to database’; // check for connectionn$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);n$sql = ‘Select * from tutorialref where id=1′;n$result = $db->query($sql);nforeach ($result as $row) {necho $row['id'] .’ – ‘. $row['author'] . ‘n’;n}n$db = null; // close the database connectionn}ncatch(PDOException $e) {necho $e->getMessage();n}nDon’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.nAbout the Author: PHP Tutorial, tips, guides. Learn PHP programming. Victor KimuranPHP Tutorial Please view the original article to properly view the code and step-by-step snapshots:PHP PDO MySQL Connect Example

theWHIR.com

About

Since 2000, The Web Host Industry Review has made a name for itself as the foremost authority of the Web hosting industry providing reliable, insightful and comprehensive news, interviews and resources to the hosting community. TheWHIR is an iNET Interactive property. For more information on iNET Interactive, visit http://www.inetinteractive.com

No related posts.

OLDER:

NEWER:

Leave a Comment

Most Recent Posts

Read Back Issues of WHIR Magazine

  • Thumbnail image for The Social Media Issue

    May 2012 - The Social Media Issue

    Read the Digital Edition – It seems rather serendipitous that, as we began preparing to launch this social media focused issue of WHIR magazine, the WHIR organization, and other iNET Interactive editorial properties began working in earnest to measure and track engagement as a metric on our websites and on the content we publish. Simply …Read More

    Read The Digital Edition
  • Thumbnail image for 2012 Hottest Hosts Directory

    February 2012 - 2012 Hottest Hosts Directory

    Read the Digital Edition – This edition of our Hottest Hosts buyer’s guide and directory issue is the fifth instance of the annual publication, a milestone that kind of snuck up on me, personally, but which I think provides an intriguing validation of the format, and of the principle behind it. The hosted services industry …Read More

    Read The Digital Edition
  • Thumbnail image for The Killer Business Model

    October 2011 - The Killer Business Model

    Read the Digital Edition – In pursuit of some inspiration for your killer business model, we sought out some of the really cool things being done in the hosting space by providers trying to stand out from the crowd. They’re not all huge companies yet, but they’ve all got some really interesting ideas, and more importantly, they’re looking at innovating in a way that could inspire some really original thinking from you.

    Read The Digital Edition