从数据库CodeIgniter加载图像

时间:2018-03-22 21:06:22

标签: codeigniter phpmyadmin photo-gallery

我想创建一个照片库,从数据库中获取图像。 我使用的是codeigniter。 Database

this is a static page located in views/pages/gallery.php

有没有人有任何想法?

2 个答案:

答案 0 :(得分:2)

您想要的是查询数据库表,获取相关字段,并将其返回到视图。在MVC中,它看起来像这样:

型号:

class Portfolio_model extends CI_Model {

    public function get_items() {
        $this->db->select('name, description, image');
        $this->db->order_by('date', 'DESC');
        $q = $this->db->get('tablename'); // your tablename here
        if ($q->num_rows() > 0) {
            return $q->result();
        } else {
            return null;
        }
    }

}

控制器:

class Portfolio extends CI_Controller {
    public function index() {
        $this->load->helper('html');
        $this->load->model('portfolio_model');
        $data['items'] = $this->portfolio_model->get_items();
        $this->load->view('portfolio', $data);
    }
}

查看:

if (!is_null($items)) {
    foreach ($items as $item) {
        echo $item->name . '<br>';
        echo $item->description . '<br>';
        echo 'Image src: ' . base_url() . $item->image . '<br>';  // might need slash after base_url, don't remember
        echo img($item->image);
    }
} else {
    echo 'No items found!';
}

答案 1 :(得分:0)

这对我有用:

控制器-

public function index(){
    $this->load->model('galleryModel');
    $data1['items'] = $this->galleryModel->get_items();
    $this->load->view('gallery', $data1);
}

模型-

public function get_items() {
    $this->db->select('*');
    $this->db->from('gallery');
    $query = $this->db->get();

    if($query->num_rows() != 0){
        return $query->result_array();
    }else{
        return false;
    }
}

查看-

<?php
    foreach ($items as $item) {       
        $image_id = $item['image_id'];       
        $name = $item['name'];
        $category = $item['category'];
        $image = $item['image'];
        ?>

    <div class="tile scale-anm <?php echo $category; ?>">
        <a href="#"><img src="<?php echo $image; ?>" class="film-img-gallery" alt="" /></a>
    </div>

<?php } ?>