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

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

5.1 Create a file: create_product.php

Go back to php-oop-crud-level-1 folder, create a file with a name create_product.php and put the following code inside it.

<?php

// set page headers

$page_title = "Create Product";

include_once "layout_header.php";

 

// contents will be here

 

// footer

include_once "layout_footer.php";

?>

5.2 Create a "Read Products" Button

The following code will render a button. Replace the comments // contents will be here of the previous section with the following.

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

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

echo "</div>";

 

?>

<!-- 'create product' html form will be here -->

<?php

5.3 Get a Database Connection

We can use it for retrieving categories or saving new product record later. Put the following code before // set page headers comment of create_product.php file.

// 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();

 

// pass connection to objects

$product = new Product($db);

$category = new Category($db);

5.4 Create the Database Configuration Class

Getting a database connection will not work without this class. This class file will be included in most PHP files of our PHP OOP CRUD Tutorial.

Create a config folder and inside that folder, create a database.php file. Open that file and put the following code.

<?php

class Database{

  

    // specify your own database credentials

    private $host = "localhost";

    private $db_name = "php_oop_crud_level_1";

    private $username = "root";

    private $password = "";

    public $conn;

  

    // get the database connection

    public function getConnection(){

  

        $this->conn = null;

  

        try{

            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);

        }catch(PDOException $exception){

            echo "Connection error: " . $exception->getMessage();

        }

  

        return $this->conn;

    }

}

?>

5.5 Create a Form in create_product.php

The following code will render an HTML form. Open create_product.php file.

Replace <!-- 'create product' html form will be here --> comment with the following code.

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

 

<!-- HTML form for creating a product -->

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

 

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

 

        <tr>

            <td>Name</td>

            <td><input type='text' name='name' class='form-control' /></td>

        </tr>

 

        <tr>

            <td>Price</td>

            <td><input type='text' name='price' class='form-control' /></td>

        </tr>

 

        <tr>

            <td>Description</td>

            <td><textarea name='description' class='form-control'></textarea></td>

        </tr>

 

        <tr>

            <td>Category</td>

            <td>

            <!-- categories from database will be here -->

            </td>

        </tr>

 

        <tr>

            <td></td>

            <td>

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

            </td>

        </tr>

 

    </table>

</form>

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

The following code will retrieve categories and put it in a "select" drop-down.

Replace <!-- categories from database will be here --> comment of the previous section with the following code.

<?php

// read the product categories from the database

$stmt = $category->read();

 

// put them in a select drop-down

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

    echo "<option>Select category...</option>";

 

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

        extract($row_category);

        echo "<option value='{$id}'>{$name}</option>";

    }

 

echo "</select>";

?>

5.7 Create the Object Class for Categories

Of course, the previous section won't work without the category object class. Create objects folder. Create category.php file. Place the following code.

<?php

class Category{

 

    // database connection and table name

    private $conn;

    private $table_name = "categories";

 

    // object properties

    public $id;

    public $name;

 

    public function __construct($db){

        $this->conn = $db;

    }

 

    // used by select drop-down list

    function read(){

        //select all data

        $query = "SELECT

                    id, name

                FROM

                    " . $this->table_name . "

                ORDER BY

                    name"; 

 

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

        $stmt->execute();

 

        return $stmt;

    }

 

}

?>

5.8 Prepare readName() method

It will get the category name instead of showing just an ID. Add the following code inside our category.php, you will see this method used in the next few sections.

// used to read category name by its ID

function readName(){

     

    $query = "SELECT name 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'];

}

5.9 Code when the Form was Submitted

The user will enter the values in the HTML form and when the create (submit) button was clicked, values will be sent via POST request, the code below will save it in the database.

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

<?php

// if the form was submitted - PHP OOP CRUD Tutorial

if($_POST){

 

    // set product property values

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

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

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

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

 

    // create the product

    if($product->create()){

        echo "<div class='alert alert-success'>Product was created.</div>";

    }

 

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

    else{

        echo "<div class='alert alert-danger'>Unable to create product.</div>";

    }

}

?>

5.10 Create the Object Class for Products

The previous section will not work without the product object. Open objects folder. Create product.php file. Open that file and put the following code.

<?php

class Product{

 

    // database connection and table name

    private $conn;

    private $table_name = "products";

 

    // object properties

    public $id;

    public $name;

    public $price;

    public $description;

    public $category_id;

    public $timestamp;

 

    public function __construct($db){

        $this->conn = $db;

    }

 

    // create product

    function create(){

 

        //write query

        $query = "INSERT INTO

                    " . $this->table_name . "

                SET

                    name=:name, price=:price, description=:description, category_id=:category_id, created=:created";

 

        $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));

 

        // to get time-stamp for 'created' field

        $this->timestamp = date('Y-m-d H:i:s');

 

        // bind values

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

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

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

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

        $stmt->bindParam(":created", $this->timestamp);

 

        if($stmt->execute()){

            return true;

        }else{

            return false;

        }

 

    }

}

?>

5.11 Output

Form to create product.

Categories drop down in the form.

Ostavite komentar

Treba vam web sajt ?

Kontakt