This article shows how to create a CRUD (Create, Read, Update, Delete) application in PHP & MySQL using PHP Data Objects (PDO). PDO is a PHP extension that provides an interface for accessing databases in PHP.
PDO is portable and powerful. There are many good features of PDO. The best one is that it’s cross-database compatible. You don’t need to change your query function if you switch database server for your project. PDO extension supports different databases like MS SQL, MySQL, Oracle, PostgreSQL, SQLite, etc.
The other benefit of PDO is error handling feature using exceptions. PDO functions can be written using try/catch block. The exceptions are logged in a log file and a user friendly error message is displayed on screen.
PDO also supports prepared statements and stored procedures. The major benefit of prepared statements is that you just need to prepare a query once and then it can be run multiple times with the same or different parameters. The other benefit is that prepared statements are quoted automatically by the driver. Hence, preventing SQL injection attack to the system/application.
In the past, I had written an article on creating a Simple CRUD System using PHP & MySQL. That article/tutorial uses MySQLi extension driver for accessing the database. In this article, we will be creating the same system but using PDO extension driver to access database.
Here is a step-by-step guide on creating a CRUD system using PHP & MySQL with PDO:
First of all, we will create a new MySQL database. Let us name the database as ‘test‘.
create database test;
Then, we will create a new table in database ‘test’. Let us name the table as ‘users‘.
use test;
CREATE TABLE users (
id int(11) NOT NULL auto_increment,
name varchar(100) NOT NULL,
age int(3) NOT NULL,
email varchar(100) NOT NULL,
PRIMARY KEY (id)
);
Now, we will create a config.php file which contains database connection code. This code connects to the MySQL database. This file is included in all PHP pages where database connection is necessary.
config.php
In below code, the database host name is localhost where username=root and password=root. The database test has been selected.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$databaseHost='localhost';
$databaseName='test';
$databaseUsername='root';
$databasePassword='root';
try{
// http://php.net/manual/en/pdo.connections.php
$dbConn=newPDO("mysql:host={$databaseHost};dbname={$databaseName}",$databaseUsername,$databasePassword);
$dbConn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);// Setting Error Mode as Exception
// More on setAttribute: http://php.net/manual/en/pdo.setattribute.php
}catch(PDOException$e){
echo$e->getMessage();
}
?>
To add data into database, we need an html form.
add.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Add DataHome
NameAgeEmailForm action on add.html is add.php. It means that the submitted form data will go to add.php. In add.php, we do a simple validation of checking if the entered name, email & age are empty or not. If they are all filled then the data will be inserted into database table.
add.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
AddData//including the database connection file
include_once("config.php");
if(isset($_POST['Submit'])){
$name=$_POST['name'];
$age=$_POST['age'];
$email=$_POST['email'];
// checking empty fields
if(empty($name)||empty($age)||empty($email)){
if(empty($name)){
echo"Name field is empty.
";
}
if(empty($age)){
echo"Age field is empty.
";
}
if(empty($email)){
echo"Email field is empty.
";
}
//link to the previous page
echo"Go Back";
}else{
// if all the fields are filled (not empty)
//insert data to database
$sql="INSERT INTO users(name, age, email) VALUES(:name, :age, :email)";
$query=$dbConn->prepare($sql);
$query->bindparam(':name',$name);
$query->bindparam(':age',$age);
$query->bindparam(':email',$email);
$query->execute();
// Alternative to above bindparam and execute
// $query->execute(array(':name' => $name, ':email' => $email, ':age' => $age));
//display success message
echo"Data added successfully.";
echo"View Result";
}
}
?>
Data from database is fetched and displayed in index.php file. This is our homepage. This file also contains a link to add data. On every row of displayed data, there is also a link to edit and delete data. Below is a sample image of our homepage:
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
$result=$dbConn->query("SELECT * FROM users ORDER BY id DESC");
?>
HomepageAddNewData
NameAgeEmailUpdatewhile($row=$result->fetch(PDO::FETCH_ASSOC)){
echo"
";echo"
".$row['name']."";echo"
".$row['age']."";echo"
".$row['email']."";echo"
Edit | Delete";}
?>
Each row of data can be edited separately. Row ID is passed in the URL of edit.php. ID uniquely identifies the data entry.
While adding data, we had two files: add.html and add.php. While editing data, I have kept the entire thing in a single edit.php file. Edit form in HTML and database update code in PHP are present in the same file.
In the code below, at first a single row entry of data is fetched based on the id. The fetched data is displayed in the edit form. When user edits the data and submits the form, then some simple validation is done for empty data. When everything is correct, then that particular entry of data is updated in database.
edit.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// including the database connection file
include_once("config.php");
if(isset($_POST['update']))
{
$id=$_POST['id'];
$name=$_POST['name'];
$age=$_POST['age'];
$email=$_POST['email'];
// checking empty fields
if(empty($name)||empty($age)||empty($email)){
if(empty($name)){
echo"Name field is empty.
";
}
if(empty($age)){
echo"Age field is empty.
";
}
if(empty($email)){
echo"Email field is empty.
";
}
}else{
//updating the table
$sql="UPDATE users SET name=:name, age=:age, email=:email WHERE id=:id";
$query=$dbConn->prepare($sql);
$query->bindparam(':id',$id);
$query->bindparam(':name',$name);
$query->bindparam(':age',$age);
$query->bindparam(':email',$email);
$query->execute();
// Alternative to above bindparam and execute
// $query->execute(array(':id' => $id, ':name' => $name, ':email' => $email, ':age' => $age));
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
?>
//getting id from url
$id=$_GET['id'];
//selecting data associated with this particular id
$sql="SELECT * FROM users WHERE id=:id";
$query=$dbConn->prepare($sql);
$query->execute(array(':id'=>$id));
while($row=$query->fetch(PDO::FETCH_ASSOC))
{
$name=$row['name'];
$age=$row['age'];
$email=$row['email'];
}
?>
EditDataHome
Name">Age">Email">>Each row of data can be deleted separately. Row ID is passed in the URL of delete.php. ID uniquely identifies the data entry. After deletion, the user is redirected to homepage (index.php).
delete.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//including the database connection file
include("config.php");
//getting id of the data from url
$id=$_GET['id'];
//deleting the row from table
$sql="DELETE FROM users WHERE id=:id";
$query=$dbConn->prepare($sql);
$query->execute(array(':id'=>$id));
//redirecting to the display page (index.php in our case)
header("Location:index.php");
?>
Hope this helps. Thanks.
Share this: