php实现类似sqlite的文件数据库示例代码
代码语言:php
所属分类:其他
代码描述:php实现类似sqlite的文件数据库示例代码
代码标签: php 类似 sqlite 文件 数据库 示例 代码
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<?php class Database { private $filename; private $tables; public function __construct($filename) { $this->filename = $filename; $this->tables = []; $this->load(); } public function createTable($name, $columns) { if (isset($this->tables[$name])) { return false; // throw new Exception("表 $name 已存在"); } $this->tables[$name] = [ 'name' => $name, 'columns' => array_merge(['id'], $columns), 'rows' => [], 'nextId' => 1 ]; return $this->save(); } public function insert($tableName, $values) { if (!isset($this->tables[$tableName])) { throw new Exception("表$tableName 不存在"); } $table = &$this->tables[$tableName]; if (count($values) + 1 !== count($table['columns'])) { throw new Exception("值的数量无效"); } $newRow = array_merge([$table['nextId']], $values); $table['rows'][] = $newRow; $table['nextId']++; return $this->save(); } public function update($tableName, $id, $updateFunc) { if (!isset($this->tables[$tableName])) { return false; //throw new Exception("表 $tableName 不存在"); } $table = &$this->tables[$tableName]; foreach ($table['rows'] as &$row) { if ($row[0] === $id) { $updatedRow = $updateFunc(array_slice($row, 1)); if (count($updatedRow) + 1 !== count($table['columns'])) { throw new Exception("更新后的值数量无效"); } $row = array_merge([$id], $updatedRow); return $this->save(); } } return false; //throw new Exception("没有找到匹配的记录".........完整代码请登录后点击上方下载按钮下载查看
网友评论0