Codeigniter 3.1.11笔记(2)

0.获取数据的active方法
这里的获取方法与前例略有不同,其一就是返回类型变成了result_array(),models/New_model.php

<?php
  class New_model extends CI_Model{

    public function database(){
      $this->load->database();
      // $sql = $this->db->query("SELECT * FROM posts");
      $sql = $this->db->where('id',1)->get('posts');
      $result = $sql->result_array();
      return $result;
      // print_r($result);
    }
  }
 ?>

views/new_view.php

hello world

<?php //print_r( $currency);
  foreach($posts as $post){
    echo $post['post_title'];
    echo '<br>';
    echo $post['post_date'];
  }
?>

1.传入参数来获取数据
首先,给单个参数:
models/New_model.php修改如下
关键在于这个参数$id,其余内容不变

<?php
  class New_model extends CI_Model{

    public function database(int $id = 1){
      $this->load->database();
      $sql = $this->db->where('id',$id)->get('posts');
      $result = $sql->result_array();
      return $result;
    }
  }
 ?>

controllers/New_con.php

	public function index(int $id = 0)
	{
    $this->load->model('New_model');
    $data['posts'] = $this->New_model->database($id);
    $this->load->view('new_view',$data);
	}

models/New_model.php

    public function database(int $id = 1){
      $this->load->database();
      // $sql = $this->db->query("SELECT * FROM posts");
      $sql = $this->db->where('id',$id)->get('posts');
      $result = $sql->result_array();
      return $result;
      // print_r($result);
    }

查看结果:http://localhost/ci3/index.php/New_con/index/2

对于多条件查询 where(['id'=>$id, 'name'=>$name])即可

Codeigniter 可以设置自动加载的model,看大家需求而定
config/autoload.php

$autoload['model'] = array('New_model');

2.插入数据
models/New_model.php

    public function create_post($ins_data)
    {
      $this->load->database();
      $this->db->insert('posts',$ins_data);
    }

controllers/New_con.php

	public function insert_post(){
		$this->load->model('New_model');

		$this->New_model->create_post([
			'post_title'=>'health is impertant',
			'post_description'=>'Jogging everday',
			'post_author'=>'john smith',
			'post_date' => '2020-06-17',
		]);
	}

http://localhost/ci3/index.php/New_con/insert_post/ 查看数据库结果即可

3.更新数据
controllers/New_con.php

	public function update_post(){
		$this->load->model('New_model');

		$this->New_model->update_post([
			'post_title'=>'health is very very impertant',
			'post_description'=>'Jogging everday every week',
			'post_author'=>'john smith',
			'post_date' => '2020-06-17',
		]);
	}

models/New_model.php

    public function update_post($ins_data)
    {
      $this->load->database();
      $this->db->where('id',3)->update('posts',$ins_data);
    }

http://localhost/ci3/index.php/New_con/update_post/ 查看数据库更新即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值