การดึงข้อมูลจาก Database ใน Codeigniter 3

โดยการที่ผมดึงจากฐานข้อมูลนั้น จะต้องสร้าง Controller ขึ้นมาเสียก่อน
ผมจะทำการเพิ่มตัว Controller Function index ที่ทำการเรียก Model ขึ้นมา

public function index()
    {
        $this->load->model('your-model');
        $data['query'] = $this->your-model->your-function();  
        $this->load->view('admin/your-view/manage', $data);
    }

หลังจากนั้นผมจะสร้าง Model ขึ้นมา ใช้ชื่อว่า Your-model
แล้วสร้างฟังชั่นขึ้นมาเป็น your-function เพื่อทำการเรียกฐานข้อมูลออกมาแสดง

$this->db->select คือการเรียกคอลั่ม
ถ้าทุกคอลั่มให้ใส่ว่า ‘*’ ถ้าเลือกบางคอลั่มให้ใส่ ‘column1’, ‘column2’, ‘column3’

$this->db->from คือการเรียกชื่อตารางที่ต้องการ

public function your-function() {
        $this->db->select('*');
        $this->db->from('tblyour');
        $query = $this->db->get();
        return $query->result();
    }

เราจะได้ $query->result(); ออกมาเพื่อแสดงผลของการเรียกแสดงข้อมูล
และให้เราใส่ foreach($query as $row)
หลังจากนั้นให้เรา echo ชื่อคอลั่มออกมาได้เลย เช่น echo $row->yourname;

<table>
    <thead>
        <tr>
            <th>#</th>
            <th>Your Name</th>
            <th>VAT Number</th>
            <th>Phone</th>
            <th>E-Mail</th>
            <th>Address</th>
            <th>Remark</th>
            <th>Date Created</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach($query as $row): ?>
        <tr>
            <td><?php echo $row->id; ?></td>
            <td><?php echo $row->yourname; ?></td>
            <td><?php echo $row->vat; ?></td>
            <td><?php echo $row->phonenumber; ?></td>
            <td><?php echo $row->email; ?></td>
            <td><?php echo $row->address; ?></td>
            <td><?php echo $row->note; ?></td>
            <td><?php echo $row->datecreated; ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

ใส่ความเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *

Up Next:

Get Post Type

Get Post Type