CRUD OOP - PHP - Xây dựng trang quản lý sản phẩm

Xây dựng trang quản lý sản phẩm

Quay lại thư mục banhang, tạo một tệp với tên create_product.php và đặt đoạn mã sau vào bên trong nó.

<?php
// set page headers
$page_title = "Create Product";
include_once "layout_header.php";
  
// contents will be here
  
// footer
include_once "layout_footer.php";
?>

Tạo Button “Read Products” 

Đoạn mã sau sẽ hiển thị một nút. Thay thế các bình luận // contents will be here of the previous section with the following.

echo "<div class='right-button-margin'>
        <a href='index.php' class='btn btn-default pull-right'>Read Products</a>
    </div>";
  
?>
<!-- 'create product' html form will be here -->
<?php

Tạo kết nối Database

Chúng ta có thể sử dụng nó để truy xuất danh mục hoặc lưu sản phẩm mới sau này. Đặt mã sau đây trước // 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);

Tạo một lớp cấu hình Database

Nhận kết nối cơ sở dữ liệu sẽ không hoạt động nếu không có lớp này. Lớp được sử dụng trong các tập PHP của chúng ta.

Tạo một thư mục config  và bên trong thư mục đó, tạo một tệp database.php. Mở tệp đó và đặt mã sau.

<?php
class Database{
   
    // specify your own database credentials
    private $host = "localhost";
    private $db_name = "banhang";
    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;
    }
}
?>

Tạo một Form  trong create_product.php

Đoạn mã sau sẽ hiển thị một biểu mẫu HTML. Mở tệp create_product.php.

Thay thế <!-- '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>

Cách hiển thị danh mục sản phẩm trong combobox 

Đoạn mã sau sẽ truy xuất các danh mục và đưa nó vào một “select”.

Thay thế <!-- categories from database will be here --> Ghi chú ở phần trước với đoạn mã sau:

<?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>";
?>

Tạo lớp đối tượng cho danh mục sản phẩm

Tất nhiên, phần trước sẽ không hoạt động nếu không có lớp đối tượng danh mục. Tạo thư mục đối tượng. Tạo tệp category.php. Đặt mã sau.

<?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;
    }
  
}
?>

Chuẩn bị phương thức readName ()

Nó sẽ nhận được tên danh mục thay vì chỉ hiển thị một ID. Thêm đoạn mã sau vào bên trong category.php, bạn sẽ thấy phương thức này được sử dụng trong một vài phần tiếp theo.

// 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'];
}

Code thêm mới sản phẩm

Người dùng sẽ nhập các giá trị trong form HTML và khi nhấp vào nút tạo (gửi), các giá trị sẽ được gửi qua yêu cầu POST, đoạn mã dưới đây sẽ lưu trong cơ sở dữ liệu.

Mở tập tin create_product.php. Thay thế  <!-- PHP post code will be here --> Chèn đoạn code sau:

<?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>";
    }
}
?>

Tạo lớp đối tượng cho sản phẩm

Phần trước sẽ không hoạt động nếu không có đối tượng sản phẩm. Mở thư mục đối tượng. Tạo tệp product.php. Mở tệp đó và đặt mã sau.

<?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;
        }
  
    }
}
?>

Xem ví dụ

Kết quả: Form tạo sản phẩm

Danh mục thả xuống trong form.

Khi bạn điền vào biểu mẫu và nhấp vào nút "Create".

Những thay đổi trong cơ sở dữ liệu.