Tutorial PHP Class For Simple CRUD with PDO For Beginners

Seegatesite.com – Step by step tutorial create php class for simple CRUD with PDO. using PDO in PHP turned out to be much easier and simpler than with mysql extention. Starting from PHP5 upgrade to Php7, requires me to learn more about the PHP PDO extension. Php7 no longer supports MySQL extension, so inevitably have to switch to PDO. Sometimes when we hear the word PDO Class, we give up yet. Apparently, using the PDO is much more comfortable and effective. I will share a tutorial php class for simple crud with pdo. To be clear, I will discuss a little bit in advance what is the PHP PDO.

Definition of PDO (PHP Data Objects)

PDO (PHP Data Objects) is a universal interface that is provided by PHP to “communicate” with the database server. You mean the term “universal interface” here is that the PDO is not tied to specific database application. If today we use the MySQL database and later want to migrate using PostgreSQL, we only stayed change how the initial call PDO and all the existing code can be directly used for the new database (this is one advantage phenomenal PDO).

Technically, if using PDO, it is not connected directly to the database, but only as an “interface”. PDO concept can be described as follows:

Tutorial PHP Class For Simple CRUD With PDO For Beginners

PDO working with a method called “a data-access abstraction layer”. That is, any type of database server that used, written PHP code will remain the same. PDO provides “abstraction layer” to communicate with the database server.

To use the PDO, we have to access it using objects. PDO does not provide a way of writing style such procedural or mysql mysqli extension (It makes us afraid to try PDO). But here I will share how I make php PDO class to use easily. I once wrote an article about Connect Bootstrap Login Form and MySQL with PDO, but how to use PDO I have not discussed in full.

Let’s start the tutorial PHP class to create crud with PDO extention.

Creating a database “crud” and a table “person”

Create Database Crud And Table Person Tutorial PHP Class For Simple CRUD With PDO For Beginners

CREATE TABLE <code>person</code> (
  <code>id_person</code> int(11) NOT NULL AUTO_INCREMENT,
  <code>name_person</code> varchar(100) DEFAULT NULL,
  <code>gender</code> enum('Male','Female') DEFAULT NULL,
  <code>country</code> varchar(50) DEFAULT NULL,
  PRIMARY KEY (<code>id_person</code>)
) 

Create PHP Class for Database Connection with PDO

Create a php file with the name dbconnect.php and copy the following code :

<?php class dbconnect { public $dbase; public function initDB() { $this->dbase = new PDO("mysql:host=localhost;dbname=crud;charset=latin1","root","123456",array(PDO::ATTR_PERSISTENT => true));
		$this->dbase->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
	}
}
?>

Explanation :

PDO("mysql:host=localhost;dbname=crud;charset=latin1","root","123456",array(PDO::ATTR_PERSISTENT => true))

  • localhost : database server location, we can change with ip address or domain
  • crud : database name
  • root : database username
  • 123456 : database password

Creating a PHP class to access CRUD with PDO

Create a php file with the name crud.php and copy the following code

<?php require_once("dbconnect.php"); class crud extends dbconnect { public function __construct() { $this->initDB();
	}
	/*Table Person*/
	public function getListPerson(){
		$db = $this->dbase;
		try
		{
			$stmt = $db->prepare("select * from person");
			$stmt->execute();
			$stat[0] = true;
			$stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
			return $stat;
		}
		catch(PDOException $ex)
		{
			$stat[0] = false;
			$stat[1] = $ex;
			return $stat;
		}
	}

	public function getPerson($id_person){
		$db = $this->dbase;
		try
		{
			$stmt = $db->prepare("select * from person where id_person = :id ");
			$stmt->bindParam("id",$id_person);
			$stmt->execute();
			$stat[0] = true;
			$stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
			return $stat;
		}
		catch(PDOException $ex)
		{
			$stat[0] = false;
			$stat[1] = $ex;
			return $stat;
		}
	}

	public function updatePerson($id_person,$name_person,$gender,$country)
	{
		$db = $this->dbase;
		try
		{
			$stmt = $db->prepare("UPDATE person SET name_person = :name ,gender = :gender,country = :country WHERE id_person = :id");
			$stmt->bindParam("id",$id_person);
			$stmt->bindParam("name",$name_person);
			$stmt->bindParam("gender",$gender);			
			$stmt->bindParam("country",$country);
			$stmt->execute();
			$stat[0] = true;
			$stat[1] = "Update Successfully";
			return $stat;
		}
		catch(PDOException $ex)
		{
			$stat[0] = false;
			$stat[1] = $ex;
			return $stat;
		}
	}

	public function savePerson($name_person,$gender,$country){
		$db = $this->dbase;
		try
		{
			$stmt = $db->prepare("INSERT INTO person(name_person,gender,country) VALUES(:name,:gender,:country)");
			$stmt->bindParam("name",$name_person);
			$stmt->bindParam("gender",$gender);
			$stmt->bindParam("country",$country);
			$stmt->execute();
			$stat[0] = true;
			$stat[1] = "Save Successfully";
			return $stat;
		}
		catch(PDOException $ex)
		{
			$stat[0] = false;
			$stat[1] = $ex;
			return $stat;
		}
	}

	public function deletePerson($id_person)
	{
		$db = $this->dbase;
		try
		{
			$stmt = $db->prepare("DELETE from person WHERE id_person = :id");
			$stmt->bindParam("id",$id_person);

			$stmt->execute();
			$stat[0] = true;
			$stat[1] = "Delete Successfully";
			return $stat;
		}
		catch(PDOException $ex)
		{
			$stat[0] = false;
			$stat[1] = $ex;
			return $stat;
		}
	}

	public function GetPersonByName($term)
	{
		$trm = "%".$term."%";
		$db = $this->dbase;
		try
		{
			$stmt = $db->prepare("select * from person where name_person like :term order by name_person asc");
			$stmt->bindParam("term",$trm);
			$stmt->execute();
			$stat[0] = true;
			$stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
			return $stat;
		}
		catch(PDOException $ex)
		{
			$stat[0] = false;
			$stat[1] = $ex;
			return $stat;
		}
	}
	public function emptyTablePerson()
	{
		$db = $this->dbase;
		try
		{
			$stmt = $db->prepare("truncate table person");
			$stmt->execute();
			$stat[0] = true;
			$stat[1] = "Delete Successfully";
			return $stat;
		}
		catch(PDOException $ex)
		{
			$stat[0] = false;
			$stat[1] = $ex;
			return $stat;
		}
	}

 /*******************************************************************************
 END OF TABEL Person
 *******************************************************************************/
}
?>

How to use php class crud :

1. Running crud php class

require_once("crud.php");
$crud = new crud();

2. Insert new data person

$save = $crud->savePerson("Sigit","Male","Indonesia");
print_r('Save Result = ');
print_r($save);

3. Update data person by id

$update = $crud->updatePerson(5,"Song Hye Kyo","Female","South Korea");
print_r('Update id 5 Result = ');
print_r($update);

4. Delete data person by id

$delete = $crud->deletePerson(2);
print_r('Delete id 2 Result = ');
print_r($delete);

5. Display all data person

$getlistperson = $crud->getListPerson();
print_r('List Person : ');
echo '
';
echo ' ID | Name | Gender | Country ';
echo '
';
foreach ($getlistperson[1] as $key ) {
	echo $key['id_person'].' | '.$key['name_person'].' | '.$key['gender'].' | '.$key['country'];
	echo '
'; } 

6. truncate table person

$crud->emptyTablePerson();

Whole of script, create new php file as index.php and copy the following code :

<?php
require_once("crud.php");

$crud = new crud();
$crud->emptyTablePerson();
$save = $crud->savePerson("Sigit","Male","Indonesia");
print_r('Save Result = ');
print_r($save);
print_r("<br>");
$save = $crud->savePerson("John Doe","Male","France");
print_r('Save Result = ');
print_r($save);
print_r("<br>");
$save = $crud->savePerson("Wang Xi","Male","China");
print_r('Save Result = ');
print_r($save);
print_r("<br>");
$save = $crud->savePerson("Tatsuya Arigato","Male","Japan");
print_r('Save Result = ');
print_r($save);
print_r("<br>");
$save = $crud->savePerson("Angela","Female","England");
print_r('Save Result = ');
print_r($save);
print_r("<br>");
$getlistperson = $crud->getListPerson();
print_r('List Person : ');
echo '<br>';
echo ' ID | Name | Gender | Country ';
echo '<br>';
foreach ($getlistperson[1] as $key ) {
	echo $key['id_person'].' | '.$key['name_person'].' | '.$key['gender'].' | '.$key['country'];
	echo '<br>';
}
print_r("<br>");
$update = $crud->updatePerson(5,"Song Hye Kyo","Female","South Korea");
print_r('Update id 5 Result = ');
print_r($update);
print_r("<br>");

$getlistperson = $crud->getListPerson();
print_r('List Person : ');
echo '<br>';
echo ' ID | Name | Gender | Country ';
echo '<br>';
foreach ($getlistperson[1] as $key ) {
	echo $key['id_person'].' | '.$key['name_person'].' | '.$key['gender'].' | '.$key['country'];
	echo '<br>';
}

print_r("<br>");
$delete = $crud->deletePerson(2);
print_r('Delete id 2 Result = ');
print_r($delete);
print_r("<br>");
$delete = $crud->deletePerson(3);
print_r('Delete id 3 Result = ');
print_r($delete);
print_r("<br>");

$getlistperson = $crud->getListPerson();
print_r('List Person : ');
echo '<br>';
echo ' ID | Name | Gender | Country ';
echo '<br>';
foreach ($getlistperson[1] as $key ) {
	echo $key['id_person'].' | '.$key['name_person'].' | '.$key['gender'].' | '.$key['country'];
	echo '<br>';
}

?>

Run these script from your browser, if successfully will display content like below

Result Tutorial PHP Class For Simple CRUD With PDO For Beginners

If you need a source code tutorial php class for simple crud using pdo , please download from the following link

Hope these article about Tutorial PHP Class For Simple CRUD with PDO For Beginners useful 🙂

The following two tabs change content below.
This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Leave a Comment

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

%d bloggers like this: