In this Article we are going to learn about PHP PDO class, which can perform Create, Read, Update and Delete (CRUD). If you don’t know about PDO please refer to the PDO reference link before heading to this article.
File Structure
Our File Structure will be as following:
Database Schema
Create Database named pdocrud
and import the following table. Use following mysql query which will create a User table with 4 fields. id
, firstname
, lastname
, and email
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
-- -- Database: `pdocrud` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(25) NOT NULL, `lastname` varchar(25) NOT NULL, `email` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; |
Configuration
In the file structure you can see the config.php
, which is our configuration file. This file is responsible for our database connection, and we also include our CRUD class here like include_once 'class.php-crud.php';
use the following code for the config.php
file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php $DB_host = "localhost";//Host $DB_user = "root";//username $DB_pass = "root";//password $DB_name = "pdocrud";//Database name try { //Database PDO connection $DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass); $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo $e->getMessage(); } //Include crud class include_once 'class.php-crud.php'; $CRUD = new CRUD($DB_con); |