PHP somo la 96: Jinsi ya kutengeneza ORM inayofanya CDRUDE operation

Katika somo hili utakwenda Jinsi ya kutengeneza ORM inayofanya CDRUDE operation.

Ufafanuzi wa Code na Structure zake

Katika somo hili, tutajifunza jinsi ya kuandika programu ya CRUD (Create, Read, Update, Delete) kwa kutumia Object-Relational Mapping (ORM) katika PHP. ORM ni njia ya kuwasiliana na database kwa kutumia madarasa na vitu badala ya maandiko ya moja kwa moja ya SQL.

Tunaingiza mafaili mawili muhimu katika programu hii:

  1. Model - Hii ni darasa la ORM linaloshughulikia mawasiliano na database. Inasaidia kutekeleza operesheni za CRUD kama create, all, find, update, na delete kwenye jedwali la database.
  2. index.php - Hii ni script kuu inayoshughulikia maombi kutoka kwa mtumiaji. Inasoma data kutoka kwa fomu na kuihifadhi kwenye database au kuonyesha taarifa kutoka kwa database.

Code Structure

  1. Model Class (model.php):

    • Database Connection: Darasa linahusisha uunganisho na database kwa kutumia Database::getInstance()->getConnection().
    • CRUD Methods: Kuna njia tano za kufanya operesheni za CRUD:
      • create($data): Inatumika kuingiza data mpya kwenye database.
      • all(): Inarejesha orodha ya taarifa zote kutoka kwenye jedwali.
      • find($id): Inapata taarifa moja kwa kutumia id kama kipengele cha kipekee.
      • update($id, $data): Inasasisha data ya mteja kwa kutumia id.
      • delete($id): Inafuta data ya mteja kwa kutumia id.
  2. Index File (index.php):

    • Form Handling: Inasimamia fomu za kuongeza, kusasisha, na kufuta wateja.
    • Displaying Data: Inawaonyesha wateja wote waliopo katika database na inatoa chaguo za kuhariri au kufuta.
    • Error Handling: Inajali hali ya kosa, kama vile kutokamilika kwa fomu au kushindwa kwa operesheni.

Code Kamili

1. Model Class (model.php)

<?php 
class Model {
    protected $db;
    protected $table;

    public function __construct($table) {
        $this->db = Database::getInstance()->getConnection();
        $this->table = $table; // Dynamically set the table name
    }

    public function create($data) {
        // Automatically generate insert query from data
        $columns = implode(", ", array_keys($data));
        $placeholders = implode(", ", array_fill(0, count($data), "?"));
        $stmt = $this->db->prepare("INSERT INTO {$this->table} ($columns) VALUES ($placeholders)");

        // Bind parameters dynamically
        $stmt->bind_param(str_repeat("s", count($data)), ...array_values($data));
        return $stmt->execute();
    }

    public function all() {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table}");
        $stmt->execute();
        return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }

    public function find($id) {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc();
    }

    public function update($id, $data) {
        $setClause = "";
        $types = "s"; // Start with "i" for id (integer)

        // Build the set clause and types string
        foreach ($data as $key => $value) {
            $setClause .= "$key = ?, ";
            $types .= "s"; // Assuming all values in $data are strings
        }
        $setClause = rtrim($setClause, ", ");

        // Prepare the SQL statement
        $stmt = $this->db->prepare("UPDATE {$this->table} SET $setClause WHERE id = ?");

        // Merge the values of $data with the id
        $params = array_merge(array_values($data), [$id]);

        // Bind parameters dynamically with the correct number of type specifiers
        $stmt->bind_param($types, ...$params); // $types now includes "i" for id and "s" for each field in $data

        return $stmt->execute();
    }

    public function delete($id) {
        $stmt = $this->db->prepare("DELETE FROM {$this->table} WHERE id = ?");
        $stmt->bind_param("i", $id);
        return $stmt->execute();
    }
}
?>

2. Index File (index.php)

<?php
require_once 'dbclass.php';
require_once "model.php";

// Initialize ORM
$customerORM = new Model('customers');
$error = "";

// Handle form submission for adding a new customer
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['action']) && $_POST['action'] === 'create') {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);

    if (!empty($name) && !empty($email)) {
        $data = [
            'name' => $name,
            'email' => $email
        ];

        if ($customerORM->create($data)) {
            header("Location: index.php");
            exit();
        } else {
            $error = "Failed to add customer.";
        }
    } else {
        $error = "Please fill in all fields.";
    }
}

// Handle form submission for updating a customer
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['action']) && $_POST['action'] === 'update') {
    $id = $_POST['id'];
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);

    if (!empty($name) && !empty($email)) {
        $data = [
            'name' => $name,
            'email' => $email
        ];

        if ($customerORM->update($id, $data)) {
            header("Location: index.php");
            exit();
        } else {
            $error = "Failed to update customer.";
        }
    } else {
        $error = "Please fill in all fields.";
    }
}

// Handle delete operation
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];

    if ($customerORM->delete($id)) {
        header("Location: index.php");
        exit();
    } else {
        $error = "Failed to delete customer.";
    }
}

// Fetch all customers
$customers = $customerORM->all();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer List</title>
</head>
<body>

<h2>Customer List</h2>
<?php if (!empty($customers)): ?>
    <table border="1">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Actions</th>
        </tr>
        <?php foreach ($customers as $customer): ?>
            <tr>
                <td><?= ht">
...

Download App Yetu

Jifunze zaidi, na wasiliana nasi ukiwa na App yetu. Bofya link hapo chini kuweza kuipakua.

Download Now Bongoclass

Nyuma Endelea


Umeionaje Makala hii.. ?

Nzuri            Mbaya            Save
Author: Rajabu image Tarehe: 1970-01-01 03:33:45 Topic: PHP Main: ICT File: Download PDF Views 94

Share On:

Facebook WhatsApp
Sponsored links
👉1 kitabu cha Simulizi    👉2 Kitabu cha Afya    👉3 Sira ya Mtume Muhammad (s.a.w)    👉4 Bongolite - Game zone - Play free game    👉5 Kitau cha Fiqh    👉6 Simulizi za Hadithi Audio   

Post zinazofanana:

PHP somo la 102: Cron job

atika somo hli tutakwenda kujifunza kuhusu kitu kinachitwa cron job. ni moja ya teknolojia zinazotumika kufanya kazi zinazofanyika automatic

Soma Zaidi...
PHP somo la 65: Jinsi ya kusoma data kwenye database kwa kutumia PDO

Katika somo hili utakwenda kujifunza jinsi ya kusoma data kwenye database kwa kutumia PDO.

Soma Zaidi...
PHP BLOG - somo la 1: Utangulizi na jinsi ya kuandaa kwa ajili ya somo

Katika course hii utakwenda kujifundisha jinsi ya lutengeneza blog kutoka mwanzo hadi mwisho.

Soma Zaidi...
PHP BLOG - somo la 3: Jinsi ya kutengeneza table kwenye databse kwa ajili ya blog

Hapa utajifunza jinsi ya kutengeneza table ambayo tutaitumia kwenye blog yetu

Soma Zaidi...
PHP - somo la 3: Maana ya variable na inavyoandika kwenye PHP

Katika somo hili utakwenda kujifunza kujusu PHP variable, maana yake na sheria za uandishi wa variable

Soma Zaidi...
PHP somol la 55: PHP Abstract Class na abstract method

Katika somo hili utakwenda kujifunza concept mpya ya abstract class na abstract method kwenye OOP.

Soma Zaidi...
PHP somo la 71: Jinsi ya kutengeneza PDF kwa kutumia PHP na library ya tcpdf

Katika somo hili utakwenda kujifunza jinsi ya ku generate PDF automatik kutoka kwenye php code , html, javascript na css.

Soma Zaidi...
PHP - somo la 4: Aina za data zinazotumika kwenye PHP

Katika somo hili utakwenda kujifunza aina za data ambazo hutumika kwenye PHP

Soma Zaidi...
PHP somo la 67: Project ya CUDE operaton wa utuma OOP na PDO

Katika somo hii utakwenda kujifunza jinsi ya kufanya CRUDE operation kwa kutumia PDO. crude operation inahusu create, read, update. Delete.

Soma Zaidi...
PHP somo la 56:class interface na polymorphism kwenye PHP OOP

Katika somo hili utakwenda kujifunza concept ya interface na concept ya polymorphism kwenye PHP OOP.

Soma Zaidi...