Sunday, March 13, 2016

Simple CRUD project with OOPHP and PDO

CRUD is an essential part for application .  At the same time for php application , combination of OOPHP and PDO will make your applications more smooth , nice , well decorated and perfect. So, I think CRUD with OOPHP and PDO is really a good practice.
In this article, I am trying to show how to create a simple project of CRUD using OOPHP and PDO.



Before reading this article , please read my previous 2 articles that related to this article -

1. Complete CRUD with PDO with PREPARED statement
2. Simple use of Composer in OOPHP - a simple Calculator with OOPHP

Ok, I think you already read this. Now lets start our next part. PDO itself object, and we are using this object inside php object.   Our projects screenshot -
In this project , I used previous folder structure that I used in Simple OOPHP project that mentioned in 2. So, the folder structure is -

Root
   |- Asset
   |----|--css
   |----|--fonts
   |----|--js
   |- Vendor
   |- src
   |----|--dbConnect
   |----|--user

To know abut Asset and Vendor folder , read my previous article.  Now, is src folder I created 2 folder, dbConnect and user . In dbConnect folder I placed dbConnect class file and in user folder I placed user class file.

I used composer.json file here too. codes in this file -

Code in composer.json file:

 ___________________________________

{
    "autoload": {
        "psr-4":{
            "oopcrud\\":"src"
        }
       
        }
}


______________________________________

To see the explanation of this file , read  my previous article and I think you already did this.

Ok, now for the application  , we need to connect our database . To do this , I used PDO in dbConnect class file. See the code in dbConnect.php file -

Code in dbConnect.php (in src/dbConnect folder)file:
____________________________________________________

<?php
namespace oopcrud\dbConnect;
use PDO;
class dbConnect
{

    public $server="server";
    public $user="username";
    public $password="password";
    public $db="dbname";
   
    public function __construct(){
        $this->conn = new PDO("mysql:host=$this->servername;dbname=$this->db", $this->user, $this->password);
        $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

}


______________________________________________

** One important thing is , I used connection code inside the "__construct()" magic method so that when its child classes are called then automatically this connection established . We can use a method to connect , then we have to call the method when a operation started in a child class method. But now we don't need to call any method to connect db.
** One more important thing is , if we use "__construct()" magic method of parent class to connect db, then when we use "__construct()" magic method in child class we have to call parent class "__construct()" method, if don't call , database connection will not be established .
** I used database connection in parent class and I will use all other database query in child class that will extended to this dbConnect class, so that our database connection codes


Ok, Now we need to create a user class to add , edit , read and delete users. codes in our user.php class file -

Code in user.php (in src/user folder)file:
___________________________________________________


<?php

namespace oopcrud\user;

use oopcrud\dbConnect\dbConnect;
use PDO;

class user extends dbConnect
{
    public $firstname="";
    public $lastname="";
    public $email="";
    public $id="";


    public function create($user){
        try {


            $this->firstname = $user['firstname'];
            $this->lastname = $user['lastname'];
            $this->email = $user['email'];

            $sql = "INSERT INTO users (firstname, lastname, email)
            VALUES (:firstname, :lastname, :email)";

            $stmt=$this->conn->prepare($sql);


            $stmt->execute(array(
                ':firstname'=>$this->firstname,
                ':lastname'=>$this->lastname,
                ':email'=>$this->email
                )
            );
           return "New record created successfully. Last ID is : ".$this->conn->lastInsertId();

        } catch (PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }
    }

    public function read(){
        try {

            $query = "SELECT * FROM users";
            $stmt = $this->conn->prepare($query);
            $stmt->execute();
            $result = $stmt->fetchAll();
           
            return $result;

        } catch (PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }           
    }

    public function update($user){
        try {


            $this->firstname = $user['firstname'];
            $this->lastname = $user['lastname'];
            $this->email = $user['email'];
            $this->id=$user['id'];

            $sql = "UPDATE users SET firstname=:firstname, lastname=:lastname, email=:email  WHERE id=:id";

            $stmt=$this->conn->prepare($sql);


            $stmt->execute(array(
                ':firstname'=>$this->firstname,
                ':lastname'=>$this->lastname,
                ':email'=>$this->email,
                ':id'=>$this->id
                )
            );
           return $stmt->rowCount() . " records UPDATED successfully";

        } catch (PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }       
       
    }

    public function delete($id){
        try {

            $this->id=$id;

            $sql = "DELETE FROM users WHERE id=:id";

            $stmt=$this->conn->prepare($sql);


            $stmt->bindparam(":id",$this->id,PDO::PARAM_STR);
            $stmt->execute();

           return "Record deleted successfully";

        } catch (PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }
       
    }
}


_________________________________________________

Our class files are ready now. We can use these class files . I will use this from index file. Code in index.php file -

Code in index.php (in root folder) file:
____________________________________________________

<?php

include_once 'vendor/autoload.php';

use oopcrud\user\user;

$user= new user;

?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>PDO CRUD Project</title>

    <!-- Bootstrap -->
    <link href="asset/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <div class="container">
        <div class="jumbotron">
            <h1>CRUD With OOP PDO</h1>
        </div>

        <div class="row">

            <div class="col-md-12">

                <form action="index.php" method="post">
                    <input type="text" name="firstname" value="" placeholder="First Name">
                    <input type="text" name="lastname" value="" placeholder="Last Name">
                    <input type="text" name="email" value="" placeholder="Email">
                    <input type="submit" name="insert" value="Submit">                   
                </form>

                 <?php

                    if(isset($_POST['update'])){
                        echo $user->update(array(
                            'firstname'=>$_POST['firstname'],
                            'lastname'=>$_POST['lastname'],
                            'email'=>$_POST['email'],
                            'id'=>$_POST['id']
                            ));
                    }
                    if(isset($_POST['insert'])){

                        echo $user->create(array(
                            'firstname'=>$_POST['firstname'],
                            'lastname'=>$_POST['lastname'],
                            'email'=>$_POST['email']
                            ));
                    }
                    if(isset($_GET['id']) && isset($_GET['action'])){
                        if($_GET['action']=='edit' ){
                            ?>
                                <form action="index.php" method="post">
                                    <input type="text" name="firstname" value="<?=$_GET['firstname']?>">
                                    <input type="text" name="lastname" value="<?=$_GET['lastname']?>">
                                    <input type="text" name="email" value="<?=$_GET['email']?>">
                                    <input type="hidden" name="id" value="<?=$_GET['id']?>">
                                    <input type="submit" name="update" value="Update">
                                </form>
                            <?php
                        }elseif($_GET['action']=='delete' ){
                            echo $user->delete($_GET['id']);
                            header('Location: ./');
                        }


                    }
                    $users=$user->read();
                    if(!empty($users)){
                            ?>
                            <table class="table table-bordered">
                            <tr>
                                <th>ID </th>
                                <th> First Name </th>
                                <th> Last Name </th>
                                <th> Email </th>
                                <th> Action </th>
                            </tr>
                            <?php
                            foreach($users as $user){
                            ?>
                            <tr>
                                <td><?=$user['id']?></td>
                                <td><?=$user['firstname']?></td>
                                <td><?=$user['lastname']?></td>
                                <td><?=$user['email']?></td>
                                <td>
                                    <a href="index.php?id=<?=$user['id']?>&action=edit&firstname=<?=$user['firstname']?>&lastname=<?=$user['lastname']?>&email=<?=$user['email']?>">Update</a>
                                    <a href="index.php?id=<?=$user['id']?>&action=delete">Delete</a>
                                </td>
                            </tr>
                    <?php } ?>
                            </table>

                            <?php

                      }
                    
                ?>
                   

            </div>                             
        </div>

    </div>


    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>-->
    <script src="asset/js/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="asset/js/bootstrap.min.js"></script>
  </body>
</html>

___________________________________________________


Thats it, our project is ready just a simple task remains. We have to execute a command from terminal or command prompt.

Open command prompt or terminal in the root folder and execute the command below -

#composer dump-autoload


Now the project is fully functional. You can run this project now.

Thanks for reading. Give your valuable opinion or comment or suggestion.



No comments:

Post a Comment