037.CI4框架CodeIgniter,使用Model模型绑定数据库表
01、我们创建一个数据库,如下:
CREATE TABLE `user` ( `id` int(20) NOT NULL AUTO_INCREMENT, `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `userpassword` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `gender` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `details` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `admin` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `group` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `age` int(3) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = MyISAM AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
02、TestUser.php代码如下:
<?php namespace App\Controllers\Test; use App\Controllers\BaseController; use CodeIgniter\API\ResponseTrait; //访问地址:http://localhost/phmci4/public/index.php/test/testuser class TestUser extends BaseController { use ResponseTrait; protected $userModel; function __construct() { $this->userModel = model('App\Models\Model_user'); } //http://localhost/phmci4/public/index.php/test/testuser/index function index() { echo "哈哈!"; } //http://localhost/phmci4/public/index.php/test/testuser/testgetuser function testgetuser() { $data = $this->userModel->getUser(); return $this->respondCreated($data); } //http://localhost/phmci4/public/index.php/test/testuser/testinsert function testinsert() { $user = array( 'username' => 'tianpan', 'userpassword' => 'guest', //如果没有在$allowedFields中,那么不会被增加和修改 'details' => 'good' ); $data = $this->userModel->insertUser($user); return $this->respondCreated($data); } }
03、Model_user.php代码如下:
<?php namespace App\Models; use CodeIgniter\Model; class Model_user extends Model { protected $table = 'user'; protected $primaryKey = 'id'; protected $allowedFields = ['username', 'userpassword']; public function getUser($id = false) { if ($id === false) { return $this->findAll(); } return $this->where(['id' => $id])->first(); } public function insertUser($data) { return $this->insert($data); } public function updateUser($data, $id) { return $this->update($id, $data); } }
04、代码结构如下:
05、访问http://localhost/phmci4/public/index.php/test/testuser/testgetuser,效果如下:
分类:
网站相关 / CI4框架
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2019-08-30 十七、库房_MB21场内移库操作