1、实现效果调用实现数据增删改查封装
2、创建数据表
CREATE TABLE `test` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(30) DEFAULT NULL,`age` int(11) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
3、index.php 入口定义数据库账号密码
<?php//定义当前请求模块
define("MODULE",'index');//定义数据库
define('DB_HOST','localhost');//数据库地址
define('DB_DATABASE','aaa');//数据库
define('DB_USER','root');//数据库账号
define('DB_PWD','root');//数据库密码require "./core/KJ.php";
4、KJ.php引入基类
//自动加载文件public static function _autoload($className){switch ($className){//自动加载控制器case substr($className,-3)=='Crl':$path= CONTROLLER.'/'.$className.'.php';if(is_file($path)) include $path;break;//自动加载基类case substr($className,-4)=='Base':$path= KJ_CORE.'/base/'.$className.'.php';if(is_file($path)) include $path;break;default :break;}}
5、基类使用pdo封装增删改查 ModelBase.php
<?php
class ModelBase
{public $pdo = NULL;public function __construct(){$this->_connect();}private function _connect(){$host = DB_HOST;$db = DB_DATABASE;$user = DB_USER;$pass = DB_PWD;$dsn = "mysql:host=$host;dbname=$db;charset=utf8";try {$this->pdo = new PDO($dsn, $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);} catch (PDOException $e) {die("数据库连接失败: " . $e->getMessage());}}public function insert($table, $data) {// 准备SQL语句$fields = implode(', ', array_keys($data));$values = ':' . implode(', :', array_keys($data));$sql = "INSERT INTO $table ($fields) VALUES ($values)";// 绑定参数并执行SQL语句$stmt = $this->pdo->prepare($sql);foreach ($data as $key => $value) {$stmt->bindValue(':' . $key, $value);}return $stmt->execute();}public function delete($table, $condition, $params = []){$sql = "DELETE FROM $table WHERE $condition";$stmt = $this->pdo->prepare($sql);foreach ($params as $key => $value) {$stmt->bindValue(":$key", $value);}$stmt->execute();return $stmt->rowCount();}public function update($table, $data, $condition, $params = []){$sql = "UPDATE $table SET ";$set = [];foreach ($data as $key => $value) {$set[] = "$key = :$key";}$sql .= implode(', ', $set);$sql .= " WHERE $condition";$stmt = $this->pdo->prepare($sql);foreach ($data as $key => $value) {$stmt->bindValue(":$key", $value);}foreach ($params as $key => $value) {$stmt->bindValue($key, $value);}$stmt->execute();return $stmt->rowCount();}public function select($table, $condition = '', $params = []){$sql = "SELECT * FROM $table";if ($condition) {$sql .= " WHERE $condition";}$stmt = $this->pdo->prepare($sql);foreach ($params as $key => $value) {$stmt->bindValue($key, $value);}$stmt->execute();return $stmt->fetchAll(PDO::FETCH_ASSOC);}
}
6、indexCrl.php控制器调用
class indexCrl{public function index(){$model= new ModelBase();// 插入数据$data = ['age' => 12,'name' => '小明',];$model->insert('test', $data);// 查询数据$result = $model->select('test', 'name = :value', [':value' => '小明']);var_dump($result);// 更新数据$data = ['age' => '13',];// 更新数据$model->update('test', $data, 'id = :id', [':id' => 1]);// 删除数据$model->delete('test', 'id = :id', ['id' => 1]);}
}
7、完整KJ.php代码
<?phpfinal class KJ{public static function run(){//定义常量self::_set_const();//创建模块目录self::_mk_module();//类自动加载spl_autoload_register(array(__CLASS__,'_autoload'));//运行框架self::_run();}//运行控制器中方法public static function _run(){$c=strtolower(isset($_GET['c'])?$_GET['c']:'index');$a=strtolower(isset($_GET['a'])?$_GET['a']:'index');$c.='Crl';if(!class_exists($c)){die("控制器".$c."不存在");}$obj=new $c();if(!method_exists($obj,$a)){die("控制器".$c."下".$a."方法不存在");}$obj->$a();}//自动加载文件public static function _autoload($className){switch ($className){//自动加载控制器case substr($className,-3)=='Crl':$path= CONTROLLER.'/'.$className.'.php';if(is_file($path)) include $path;break;//自动加载基类case substr($className,-4)=='Base':$path= KJ_CORE.'/base/'.$className.'.php';if(is_file($path)) include $path;break;default :break;}}//定义常量public static function _set_const(){//获取框架核心路径 都替换/以便兼容linux$path=str_replace('\\','//',__FILE__);//定义常量define("KJ_CORE",dirname($path)); //框架核心路径define('ROOT_PATH',dirname(KJ_CORE));//项目根目录define('MODULE_PATH',ROOT_PATH.'/'.MODULE);//模块define('CONTROLLER',MODULE_PATH.'/controller');//定义控制器define('MODEL',MODULE_PATH.'/model');//定义模型define('VIEW',MODULE_PATH.'/view');//定义显示成}//自动创建模块目录public static function _mk_module(){$arr=[MODULE_PATH,CONTROLLER,MODEL,VIEW,];foreach ($arr as $v){is_dir($v) || mkdir($v,0777,true);}}}
KJ::run();