PHP OOP CRUD Tutorial – Step By Step Guide! Part 8
Dodato 2 months ago u OOP PHP od Milan Janković

PHP OOP CRUD Tutorial – Step By Step Guide! Part 8

7.0 UPDATING RECORD IN PHP THE OOP WAY

I know our PHP OOP CRUD tutorial is kinda long. Please take a break or drink some coffee first!

7.1 Create File: update_product.php

Create update_product.php file, open that file and put the following code.

9.0 DELETING RECORD IN PHP THE OOP WAY

This is the last coding part of our PHP OOP CRUD Tutorial. Enjoy every code!

9.1 Put this JavaScript code in layout_footer.php

Put the following JavaScript code before the closing "body" tag in layout_footer.php file. We used Bootbox.js to make a Bootstrap-style confirm dialog box.

<script>

// JavaScript for deleting product

$(document).on('click', '.delete-object', function(){

 

    var id = $(this).attr('delete-id');

 

    bootbox.confirm({

        message: "<h4>Are you sure?</h4>",

        buttons: {

            confirm: {

                label: '<span class="glyphicon glyphicon-ok"></span> Yes',

                className: 'btn-danger'

            },

            cancel: {

                label: '<span class="glyphicon glyphicon-remove"></span> No',

                className: 'btn-primary'

            }

        },

        callback: function (result) {

 

            if(result==true){

                $.post('delete_product.php', {

                    object_id: id

                }, function(data){

                    location.reload();

                }).fail(function() {

                    alert('Unable to delete.');

                });

            }

        }

    });

 

    return false;

});

</script>

9.2 Create delete_product.php

Create a new file and name it "delete_product.php". This file accepts the ID posted by the JavaScript code in the previous section. A record will be deleted from the database based on posted ID.

Open delete_product.php and put the following code.

<?php

// check if value was posted

if($_POST){

 

    // include database and object file

    include_once 'config/database.php';

    include_once 'objects/product.php';

 

    // get database connection

    $database = new Database();

    $db = $database->getConnection();

 

    // prepare product object

    $product = new Product($db);

     

    // set product id to be deleted

    $product->id = $_POST['object_id'];

     

    // delete the product

    if($product->delete()){

        echo "Object was deleted.";

    }

     

    // if unable to delete the product

    else{

        echo "Unable to delete object.";

    }

}

?>

9.3 Delete Code in Product Class

The previous section will not work with the "delete()" method in the product object. Open "product.php" which is inside the "objects" folder and put the following code.

// delete the product

function delete(){

 

    $query = "DELETE FROM " . $this->table_name . " WHERE id = ?";

     

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

    $stmt->bindParam(1, $this->id);

 

    if($result = $stmt->execute()){

        return true;

    }else{

        return false;

    }

}

9.4 Output

Click any "Delete" button in the index page. A pop up confirmation will be shown.

If the user clicks "OK" the record will be deleted and gone in the table.

A record was deleted in the database.

10.0 SEARCH RECORDS IN PHP THE OOP WAY

We'll continue by adding the search feature. This will answer the question: How to search data from database in php? This is a very useful feature because you enable your users to easily search a certain data from our MySQL database.

Please note that this is a bonus section. The code in this section is not included in our LEVEL 1 source code download.

10.1 Change index.php

We have to change index.php because we are adding a “search” feature and we want our code to be short. Our index.php will now look like the following code.

<?php

// core.php holds pagination variables

include_once 'config/core.php';

 

// include database and object files

include_once 'config/database.php';

include_once 'objects/product.php';

include_once 'objects/category.php';

 

// instantiate database and product object

$database = new Database();

$db = $database->getConnection();

 

$product = new Product($db);

$category = new Category($db);

 

$page_title = "Read Products";

include_once "layout_header.php";

 

// query products

$stmt = $product->readAll($from_record_num, $records_per_page);

 

// specify the page where paging is used

$page_url = "index.php?";

 

// count total rows - used for pagination

$total_rows=$product->countAll();

 

// read_template.php controls how the product list will be rendered

include_once "read_template.php";

 

// layout_footer.php holds our javascript and closing html tags

include_once "layout_footer.php";

?>

10.2 Create read_template.php

Why do we need this template? We need it because exactly the same code can be used by index.php and search.php for displaying a list of records. Using a template means lesser code.

This template holds our search form as well.

<?php

// search form

echo "<form role='search' action='search.php'>";

    echo "<div class='input-group col-md-3 pull-left margin-right-1em'>";

        $search_value=isset($search_term) ? "value='{$search_term}'" : "";

        echo "<input type='text' class='form-control' placeholder='Type product name or description...' name='s' id='srch-term' required {$search_value} />";

        echo "<div class='input-group-btn'>";

            echo "<button class='btn btn-primary' type='submit'><i class='glyphicon glyphicon-search'></i></button>";

        echo "</div>";

    echo "</div>";

echo "</form>";

 

// create product button

echo "<div class='right-button-margin'>";

    echo "<a href='create_product.php' class='btn btn-primary pull-right'>";

        echo "<span class='glyphicon glyphicon-plus'></span> Create Product";

    echo "</a>";

echo "</div>";

 

// display the products if there are any

if($total_rows>0){

 

    echo "<table class='table table-hover table-responsive table-bordered'>";

        echo "<tr>";

            echo "<th>Product</th>";

            echo "<th>Price</th>";

            echo "<th>Description</th>";

            echo "<th>Category</th>";

            echo "<th>Actions</th>";

        echo "</tr>";

 

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){

 

            extract($row);

 

            echo "<tr>";

                echo "<td>{$name}</td>";

                echo "<td>{$price}</td>";

                echo "<td>{$description}</td>";

                echo "<td>";

                    $category->id = $category_id;

                    $category->readName();

                    echo $category->name;

                echo "</td>";

 

                echo "<td>";

 

                    // read product button

                    echo "<a href='read_one.php?id={$id}' class='btn btn-primary left-margin'>";

                        echo "<span class='glyphicon glyphicon-list'></span> Read";

                    echo "</a>";

 

                    // edit product button

                    echo "<a href='update_product.php?id={$id}' class='btn btn-info left-margin'>";

                        echo "<span class='glyphicon glyphicon-edit'></span> Edit";

                    echo "</a>";

 

                    // delete product button

                    echo "<a delete-id='{$id}' class='btn btn-danger delete-object'>";

                        echo "<span class='glyphicon glyphicon-remove'></span> Delete";

                    echo "</a>";

 

                echo "</td>";

 

            echo "</tr>";

 

        }

 

    echo "</table>";

 

    // paging buttons

    include_once 'paging.php';

}

 

// tell the user there are no products

else{

    echo "<div class='alert alert-danger'>No products found.</div>";

}

?>

10.3 Create core.php in "config" folder

Create a new folder and name it "config". Inside that folder, create a new file and name it "core.php".

This file will hold our pagination variables. Using a core.php file is a good practice, it can be used to hold other configuration values that you might need in the future.

Open core.php and put the following code.

<?php

// page given in URL parameter, default page is one

$page = isset($_GET['page']) ? $_GET['page'] : 1;

 

// set number of records per page

$records_per_page = 5;

 

// calculate for the query LIMIT clause

$from_record_num = ($records_per_page * $page) - $records_per_page;

?>

10.4 Change paging.php code

The new paging.php code will look like the following.

<?php

echo "<ul class=\"pagination\">";

 

// button for first page

if($page>1){

    echo "<li><a href='{$page_url}' title='Go to the first page.'>";

        echo "First Page";

    echo "</a></li>";

}

 

// count all products in the database to calculate total pages

$total_pages = ceil($total_rows / $records_per_page);

 

// range of links to show

$range = 2;

 

// display links to 'range of pages' around 'current page'

$initial_num = $page - $range;

$condition_limit_num = ($page + $range)  + 1;

 

for ($x=$initial_num; $x<$condition_limit_num; $x++) {

 

    // be sure '$x is greater than 0' AND 'less than or equal to the $total_pages'

    if (($x > 0) && ($x <= $total_pages)) {

 

        // current page

        if ($x == $page) {

            echo "<li class='active'><a href=\"#\">$x <span class=\"sr-only\">(current)</span></a></li>";

        }

 

        // not current page

        else {

            echo "<li><a href='{$page_url}page=$x'>$x</a></li>";

        }

    }

}

 

// button for last page

if($page<$total_pages){

    echo "<li><a href='" .$page_url . "page={$total_pages}' title='Last page is {$total_pages}.'>";

        echo "Last Page";

    echo "</a></li>";

}

 

echo "</ul>";

?>

7.2 Create a "Read Products" Button

The following code will render a button. This button, when clicked, will let us go back to the records list. Replace the previous section's "contents will be here" comments with the following code.

echo "<div class='right-button-margin'>";

    echo "<a href='index.php' class='btn btn-default pull-right'>Read Products</a>";

echo "</div>";

7.3 Retrieve One Product Information Based on the Given ID.

The following code will retrieve data that will populate our HTML form. This is important because this will let the user know what exactly the record he is updating.

Open update_product.php file. Replace "// retrieve one product will be here" comment with the following code.

// get ID of the product to be edited

$id = isset($_GET['id']) ? $_GET['id'] : die('ERROR: missing ID.');

 

// include database and object files

include_once 'config/database.php';

include_once 'objects/product.php';

include_once 'objects/category.php';

 

// get database connection

$database = new Database();

$db = $database->getConnection();

 

// prepare objects

$product = new Product($db);

$category = new Category($db);

 

// set ID property of product to be edited

$product->id = $id;

 

// read the details of product to be edited

$product->readOne();

 

?>

<!-- 'update product' form will be here -->

<?php

7.4 Add readOne() method in the Product Object Class.

The readOne() method used in the previous section will not work without the following code inside /objects/product.php file.

function readOne(){

 

    $query = "SELECT

                name, price, description, category_id

            FROM

                " . $this->table_name . "

            WHERE

                id = ?

            LIMIT

                0,1";

 

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

    $stmt->bindParam(1, $this->id);

    $stmt->execute();

 

    $row = $stmt->fetch(PDO::FETCH_ASSOC);

 

    $this->name = $row['name'];

    $this->price = $row['price'];

    $this->description = $row['description'];

    $this->category_id = $row['category_id'];

}

7.5 Put the Values in the Form.

Now we can put the latest values to each form elements. Replace "<!-- 'update product' form will be here -->" comment of update_product.php with the following code.

<!-- post code will be here -->

 

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"] . "?id={$id}");?>" method="post">

    <table class='table table-hover table-responsive table-bordered'>

 

        <tr>

            <td>Name</td>

            <td><input type='text' name='name' value='<?php echo $product->name; ?>' class='form-control' /></td>

        </tr>

 

        <tr>

            <td>Price</td>

            <td><input type='text' name='price' value='<?php echo $product->price; ?>' class='form-control' /></td>

        </tr>

 

        <tr>

            <td>Description</td>

            <td><textarea name='description' class='form-control'><?php echo $product->description; ?></textarea></td>

        </tr>

 

        <tr>

            <td>Category</td>

            <td>

                <!-- categories select drop-down will be here -->

            </td>

        </tr>

 

        <tr>

            <td></td>

            <td>

                <button type="submit" class="btn btn-primary">Update</button>

            </td>

        </tr>

 

    </table>

</form>

7.6 Loop Through the Categories Records to show as Drop-down

The following code will list the categories in a drop-down.

Notice that we put "if($product->category_id==$category_id){..." inside the while loop. This is to pre-select the option of the current record.

Replace the previouse section's comments "categories select drop-down will be here" with the following code.

<?php

$stmt = $category->read();

 

// put them in a select drop-down

echo "<select class='form-control' name='category_id'>";

 

    echo "<option>Please select...</option>";

    while ($row_category = $stmt->fetch(PDO::FETCH_ASSOC)){

        $category_id=$row_category['id'];

        $category_name = $row_category['name'];

 

        // current category of the product must be selected

        if($product->category_id==$category_id){

            echo "<option value='$category_id' selected>";

        }else{

            echo "<option value='$category_id'>";

        }

 

        echo "$category_name</option>";

    }

echo "</select>";

?>

7.7 Code When Form was Submitted

The following code will assign the "posted" values to the object properties. Once assigned, it will update the database with those values using the update() method.

Open update_product.php file. Replace <!-- post code will be here -->" comment with the following code.

<?php

// if the form was submitted

if($_POST){

 

    // set product property values

    $product->name = $_POST['name'];

    $product->price = $_POST['price'];

    $product->description = $_POST['description'];

    $product->category_id = $_POST['category_id'];

 

    // update the product

    if($product->update()){

        echo "<div class='alert alert-success alert-dismissable'>";

            echo "Product was updated.";

        echo "</div>";

    }

 

    // if unable to update the product, tell the user

    else{

        echo "<div class='alert alert-danger alert-dismissable'>";

            echo "Unable to update product.";

        echo "</div>";

    }

}

?>

7.8 Update Code in the Product Class

The following code will make the previous section's "$product->update()" method work. Open our "product.php" which is inside the "objects" folder and add the following code.

function update(){

 

    $query = "UPDATE

                " . $this->table_name . "

            SET

                name = :name,

                price = :price,

                description = :description,

                category_id  = :category_id

            WHERE

                id = :id";

 

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

 

    // posted values

    $this->name=htmlspecialchars(strip_tags($this->name));

    $this->price=htmlspecialchars(strip_tags($this->price));

    $this->description=htmlspecialchars(strip_tags($this->description));

    $this->category_id=htmlspecialchars(strip_tags($this->category_id));

    $this->id=htmlspecialchars(strip_tags($this->id));

 

    // bind parameters

    $stmt->bindParam(':name', $this->name);

    $stmt->bindParam(':price', $this->price);

    $stmt->bindParam(':description', $this->description);

    $stmt->bindParam(':category_id', $this->category_id);

    $stmt->bindParam(':id', $this->id);

 

    // execute the query

    if($stmt->execute()){

        return true;

    }

 

    return false;

     

}

7.9 Output

Click any "Edit" button in the index page. The update record form should look like the following.

When you submit the form, a message will be shown.

A record was changed in the database.

8.0 READ ONE RECORD IN PHP THE OOP WAY

We previously made the code for "update record", this section for reading one record from a database will be easier to do.

8.1 Create read_one.php file

This is the page where the data of a single record will be displayed. Create a new file and name it "read_one.php", open that file and put the following code.

<?php

// set page headers

$page_title = "Read One Product";

include_once "layout_header.php";

 

// read products button

echo "<div class='right-button-margin'>";

    echo "<a href='index.php' class='btn btn-primary pull-right'>";

        echo "<span class='glyphicon glyphicon-list'></span> Read Products";

    echo "</a>";

echo "</div>";

 

// set footer

include_once "layout_footer.php";

?>

8.2 Read one record based on given record ID

The following code will read a single record from the database. Put the following code before the "set page headers" comments of the previous section.

// get ID of the product to be read

$id = isset($_GET['id']) ? $_GET['id'] : die('ERROR: missing ID.');

 

// include database and object files

include_once 'config/database.php';

include_once 'objects/product.php';

include_once 'objects/category.php';

 

// get database connection

$database = new Database();

$db = $database->getConnection();

 

// prepare objects

$product = new Product($db);

$category = new Category($db);

 

// set ID property of product to be read

$product->id = $id;

 

// read the details of product to be read

$product->readOne();

8.3 Display record on HTML table

This time, we will display the record details on an HTML table. Put the following code under the closing "div" tag of "Read Products" button.

// HTML table for displaying a product details

echo "<table class='table table-hover table-responsive table-bordered'>";

 

    echo "<tr>";

        echo "<td>Name</td>";

        echo "<td>{$product->name}</td>";

    echo "</tr>";

 

    echo "<tr>";

        echo "<td>Price</td>";

        echo "<td>&#36;{$product->price}</td>";

    echo "</tr>";

 

    echo "<tr>";

        echo "<td>Description</td>";

        echo "<td>{$product->description}</td>";

    echo "</tr>";

 

    echo "<tr>";

        echo "<td>Category</td>";

        echo "<td>";

            // display category name

            $category->id=$product->category_id;

            $category->readName();

            echo $category->name;

        echo "</td>";

    echo "</tr>";

 

echo "</table>";

8.4 Output

Click any "Read" button in the index page, you should see something like the image below.

Ostavite komentar

Treba vam web sajt ?

Kontakt