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

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

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.

<?php

// retrieve one product will be here

 

// set page header

$page_title = "Update Product";

include_once "layout_header.php";

 

// contents will be here

 

// set page footer

include_once "layout_footer.php";

?>

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