首页 > 解决方案 > 如何使用 CodeIgniter 在主页中动态获取/查看图像?

问题描述

图片

New_model
=========

   <?php defined('BASEPATH') OR exit('No direct script access allowed');

class New_model extends CI_Model
{
    private $_table = "news";

    public $title;
    public $date;
    public $description;
    public $image = "default.jpg";
    public $url;


    public function rules()
    {
        return [
            ['field' => 'title',
            'label' => 'Title',
            'rules' => 'required'],

            ['field' => 'date',
            'label' => 'Date',],
            // 'rules' => 'required'],

            ['field' => 'description',
            'label' => 'Description',
            'rules' => 'required']
        ];
    }

    public function getAll()
    {
        return $this->db->get($this->_table)->result();
    }

    public function getById($id)
    {
        return $this->db->get_where($this->_table, ["new_id" => $id])->row();
    }

    public function save()
    {
         $post = $this->input->post();
         // $this->new_id = uniqid();
         $this->title = $post["title"];
         $this->date = $post["date"];
         $this->description = $post["description"];
         $this->image = $this->_uploadImage();
         $this->db->insert($this->_table, $this);
         // $this->url = base_url() . 'uploads/';
         $post['url'] = base_url() . 'uploads/';
    }

    public function update()
    {
        $post = $this->input->post();
        $this->new_id = $post["id"];
        $this->title = $post["title"];
        $this->date = $post["date"];
        $this->description = $post["description"];


        if (!empty($_FILES["image"]["name"])) {
             $this->image = $this->_uploadImage();
        } else {
             $this->image = $post["old_image"];
        }


         $this->db->update($this->_table, $this, array('new_id' => $post['id']));
     }

     public function delete($id)
     {
        $this->_deleteImage($id);
         return $this->db->delete($this->_table, array("new_id" => $id));
     }

     private function _uploadImage()
    {
        $config['upload_path']          = './uploads/';
        $config['allowed_types']        = 'gif|jpg|png|jpeg';
         // $config['file_name']            = $this->new_id;
        $config['overwrite']            = true;
        $config['max_size']             = 1024; // 1MB
        // $config['max_width']            = 1024;
        // $config['max_height']           = 768;

        $this->load->library('upload', $config);

        if ($this->upload->do_upload('image')) {
            return $this->upload->data("file_name");
        }

        return "default.jpg";
     }

     private function _deleteImage($id)
     {
           $new = $this->getById($id);
           if ($new->image != "default.jpg") {
           $filename = explode(".", $new->image)[0];
           return array_map('unlink', glob(FCPATH."uploads/$filename.*"));
        }
     }

}

public function single($id)
        {
            $data['news'] = $this->New_model->where('new_id',$id)->order_by('new_id','desc')->get_all();
            $data['news1'] = $this->New_model->limit(5)->order_by('id','desc')->get_all();
            $this->current = 'news';
            $this->load->view(['current' => $this->current]);

            $this->load->view('news',$data);
        }


Controller
==========
public function index()
    {       
        $data["news"] = $this->New_model->getAll();
        $this->load->view('index',$data);
    }

public function latestnews()
        {   
           $data['news'] = $this->New_model->where('new_id',$id)->order_by('new_id','desc')->get_all();
           $this->load->view('news',$data);
        }


view
====
 <?php
                        if (isset($news) and $news) {
                            foreach ($news as $new) {
                            ?>
                                <div class="tile-primary-content">
                                    <img  src="<?php echo $new->url . $new->image;?>" alt="image" />
                                </div>
                                <div class="tile-secondary-content">
                                    <div class="section-title-1">                                     
                                       <span class="title"><?php echo $new->title;?></span>                                      
                                     </div>            
                                    <h2 class="heading-20"><?php echo $new->date;?></h2>
                                </div>    

                            <?php
                            }
                        }
                        ?>

我正在尝试在仪表板中上传带有标题和日期的图像以及图像上传。

  1. 如何在主页上显示该图像?
  2. 如何在 New_model 中设置 URL?
  3. 如何设置链接以显示主页中的图像?
  4. 如何设置日期链接?
  5. 在首页可以查看标题字段,但是没有图片和日期……</li>

标签: codeigniter

解决方案


试试这个代码。

控制器:(已编辑)

   function index() {
        $this->data["news"] = $this->new_model->getAll();
        $this->load->view('index', $this->data);
   }

   function single_news($id) {
      $this->data['news_data'] = $this->new_model->getNewsByID($id);
      $this->load->view('single-news', $this->data); // Create New View file named single-news.php
   }

   function add_news() {
        $image_status = FALSE;
        $this->load->library('form_validation');

        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('description', 'Description', 'required');

        if($this->form_validation->run() == TRUE) {
            $image_name = NULL;
            if ($_FILES['image']['size'] > 0) {
                $this->load->library('upload');

                $config['upload_path'] = 'uploads/';
                $config['allowed_types'] = 'gif|jpg|png|jpeg';
                $config['max_size'] = '1024';
                $config['overwrite'] = TRUE;

                $this->upload->initialize($config);

                if( ! $this->upload->do_upload('image')){
                    $this->data['error'] = $this->upload->display_errors();
                }

                $image_name = $this->upload->file_name;
                $image_status = TRUE;
            }

            $data = array(
                'title' => $this->input->post('title'),
                'date' => $this->input->post('date')?date('Y-m-d', strtotime($this->input->post('date'))):NULL,
                'description' => $this->input->post('description'),
                'image' => $image_name
            );
        }
        if($this->form_validation->run() == TRUE && $image_status && $this->new_model->addNews($data)) {
            $this->session->set_flashdata('message', 'News has been created successfully.');
            redirect('index');
        } else {
            $this->data['error'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
            $this->data['page_title'] = 'Add News';
            $this->load->view('add_news', $this->data);
        }
    }

添加新新闻时,您不需要添加上传的位置(不需要)。

型号:(已编辑)

function getAll() {
   $q = $this->db->get('news');
   if($q->num_rows() > 0) {
      foreach($q->result() as $row) {
        $data[] = $row;
      }
      return $data;
   }
  return false;
}

function getNewsByID($id) {
   $this->db->where('id', $id);
   $q = $this->db->get('news');
   if($q->num_rows() > 0) {
      return $q->row();
   }
  return false;
}

function addNews($data) {
   if($this->db->insert('news', $data)){
     return true;
   }
   return false;
}

视图:(已编辑)

<?php
     if ($news) {
       foreach ($news as $new) {
?>
        <div class="tile-primary-content">
          <a href="<?php echo base_url('single_news/'.$new->id); ?>"
          <img  src="<?php echo site_url('uploads/'.$new->image); ?>" alt="image" />
          </a>
        </div>
        <div class="tile-secondary-content">
          <div class="section-title-1">                                     
            <span class="title"><?php echo $new->title;?></span>                                      
          </div>            
          <h2 class="heading-20"><?php echo !is_null($new->date)?date('d.m.Y', strtotime($new->date)):' - ';?></h2>
        </div>    
<?php
      }
   }
?>

single-news.php: (查看)

...
<img src="<?php echo site_url('uploads/'.$news_data->image); ?>" />
...

推荐阅读