Since the deprecation of mysql_ function in PHP, developers are advised to use mysqli_ or PDO in order to connect to databases. The main feature of PDO is that it can be used with every database provider. In this tutorial I will be using PDO to connect with MySQL. My emphasis would be on the object oriented approach.
Some users, particularly beginners, find PDO difficult to use because of its syntax hence the need for this two-part tutorial. In the first part , I will connect with the database using PDO and perform CRUD operations, paying special attention to SQL injection threats. In the second part, I will discuss how prepaid statements work with PDO.
Letâ€™s get started with the first part.
Table Of Content
1. Creating A Database
Letâ€™s create a database and a table for CRUD operation using PDO. Name your database pdotutorial and create a table user with the following schema:
2. Creating A Connection Class
First, I will create a separate class for PDO connection for the database. This call will be called everytime the code needs to connect to the database and perform operations. Create a new class Connection. Add the following code to the file and save it withe the name connection.php.
Letâ€™s understand the above code step by step.
First, I saved the database credentials in variables. Next, the important variable $options:
In above line, I set the error mode and data fetch mode on runtime so that I do not have to worry about defining it at every SQL query. Near the end, I created the connection and return it.
Letâ€™s test the class. Create a new file in the same directory and name it index.php. Now paste the following code in it and run it.
Now, I am successfully connected to database.
3. Performing Database Queries
It is now time for CRUD operations. Started by saving data in the database.
Saving the Data
In index.php, replace the code with this:
When you run the file, data will inserted in the database.
Fetching the Data
Now that there is data in the database, it is time to fetch the data. Add the following code to index.php:
On running the file, the code will fetch the data.
Getting the Number of Affected Rows In PDO
In the case of update, it is important to know the number of the data rows that will be affected by the update statement. Letâ€™s perform this in PDO by replacing the code in index.php with the following code.
4. The End
This is the end of first part of the PDO tutorial series. In the next part, I will perform the same queries using prepared statements. If you have a question or wish to add to the discussion, please leave a comment.
Hopefully this simple tutorial helped you with your development.
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.