PHP PDO Basics - Coding Cyber

PHP PDO Basics

In this step, you will learn about basic operations in PHP PDO that is connecting to the database with PDO and also writing first SQL query, displaying error messages efficiently in PHP PDO. you will learn these 3 topics in this step with PHP PDO.

Other Articles in Learn PHP PDO

1. Connecting to Database

In PHP PDO, we can connect to the database by creating new PDO object and we have to pass database type, hostname, database name, database username, database password.

Here I’ve created a DSN variable with database type, here I’m using the MySQL database. And the hostname is localhost, use your hostname here. Next value is database name.

I’m creating database object by instantiating PDO with dsn variable and database username, password.

Here is the code you can use. Save it as the connect.php file.

2. First Query in PHP PDO

Here in this step, you will learn how to write first select SQL query and print the fetched records with the print_r PHP function.

I’m using the database table form previous PHP CRUD application. You can use the same table form this article.

Here I’m using query method to execute this select SQL query. After that, I’m assigning to $rows.

This query method only works with foreach loop. I’m using while loop with $rows to get result array. This result array contains result as both numeric array and associative array.

As an example to echo the records, here I’m using an associative array and numeric array with first name and the last name with numeric pocket 2. After putting this code in foreach loop all the full names will be displayed in the browser.

3. Working with Errors in PHP PDO

Previously you ran simple SQL query if you change the DB name to something else. You won’t get the correct error message what is wrong with the code.

To get correct error messages, we should catch the errors for that I’ll use a try-catch block. We can catch the errors in two ways that are using the setAttribute method and with the errorInfo method.

Here you learn about both methods. Inside try block I’m using the require_once PHP function to load the connect.php file and after that setting error mode with the setAttribute method.

In catch method, I’m assigning the exception to $e, then catching the errors with exception getMessage method.

If error variable is set, You will see the error messages in browser.

The second method is using the erroInfo method to get the errors, and the actual errors are in the second pocket, so here I’m assigning pocket 2 value to error variable.

If error variable is set, You will see the error messages in browser.

You can use any one of these methods to get correct error messages.

Related Posts
No related posts for this content
Vivek Vengala
 

Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: