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/ 查看数据库结果即可
扫描二维码关注公众号,回复:
12422277 查看本文章

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/ 查看数据库更新即可。