PHP实现使用txt文本作为数据库 php文本数据库操类
php文本数据库操类
<?php /** * 文本数据库类类,用于将txt文本文件作为数据库,实现增删改查功能 * 源码下载: http://www.wdphp.com * Author: 缘境 (yvsm@163.com) QQ:316430983 */ class TextDatabase { private $filename; public function __construct($filename) { $this->filename = $filename; } // 定义一个名为insert的方法,接受一个数据数组并将其附加到文本文件的末尾 public function insert($data) { // 以追加模式打开文件 $handle = fopen($this->filename, 'a'); fwrite($handle, implode(',', $data) . "\n"); fclose($handle); } // 定义一个名为selectAll的方法,返回文本文件中所有数据的数组 public function selectAll() { // 以读取模式打开文件 $handle = fopen($this->filename, 'r'); $data = array(); // 逐行循环读取文件 while (!feof($handle)) { $line = fgets($handle); if (!empty($line)) { $data[] = explode(',', $line); } } fclose($handle); return $data; } // 定义一个名为update的方法,接受一个数据数组并更新文本文件中相应的记录 public function update($data) { // 以读取模式打开文件 $handle = fopen($this->filename, 'r'); $updatedData = array(); while (!feof($handle)) { $line = fgets($handle); if (!empty($line)) { $record = explode(',', $line); if ($record[0] == $data[0]) { $updatedData[] = implode(',', $data) . "\n"; } else { $updatedData[] = $line; } } } fclose($handle); $handle = fopen($this->filename, 'w'); fwrite($handle, implode('', $updatedData)); fclose($handle); } // 定义一个名为delete的方法,接受一个ID并从文本文件中删除相应的记录 public function delete($id) { $handle = fopen($this->filename, 'r'); $updatedData = array(); while (!feof($handle)) { $line = fgets($handle); if (!empty($line)) { $record = explode(',', $line); if ($record[0] != $id) { $updatedData[] = $line; } } } fclose($handle); $handle = fopen($this->filename, 'w'); fwrite($handle, implode('', $updatedData)); fclose($handle); } // 定义一个名为select的方法,接受一个ID并返回文本文件中相应的记录 public function select($id) { // 以读取模式打开文件 $handle = fopen($this->filename, 'r'); // 逐行循环读取文件 while (!feof($handle)) { // 从文件中读取一行 $line = fgets($handle); // 如果行不为空,则检查它是否与要查询的ID匹配 if (!empty($line)) { $record = explode(',', $line); // 如果记录与要查询的ID匹配,则返回该记录 if ($record[0] == $id) { // 关闭文件 fclose($handle); // 返回记录 return $record; } } } fclose($handle); } }
使用示例
// 使用文件名"data.txt"创建TextDatabase类的新实例 $textDatabase = new TextDatabase('data.txt'); // 将新记录插入文本文件 $textDatabase->insert(array(1, 'John Doe', 'johndoe@wdphp.com')); $find = $textDatabase->select(1); print_r($find); // 更新文本文件中的现有记录 $textDatabase->update(array(1, 'wdphp', 'yvsm@wdphp.com')); // 从文本文件中删除记录 $textDatabase->delete(1); // 选择文本文件中的所有记录 $data = $textDatabase->selectAll(); // 打印数据 print_r($data);
后语
使用文本数据库并不是一个很好的选择,或许一些特殊环境下可以用到吧~~
MySQL、SQLite、MongoDB、PgSQL都是比较好的选择
相关内容
这些是最新的
热门排行
- THINKPHP5+GatewayWorker+Workerman 开发在线客服系统
- 在手机浏览器网页中点击链接跳转到微信界面的方法
- 尊云网站目录系统 ThinkPHP5网站分类目录程序 v2.2.221011
- CentOS 7安装shadowsock(一键安装脚本)
- AdminTemplate 基于LayUI 2.4.5实现的网站后台管理模板
- 用NW.js(node-webkit)开发多平台的桌面客户端
- PHP生成随机昵称/用户名
- THINKPHP5网站分类目录程序 尊云网站目录系统
- 织梦(DEDECMS)微信支付接口 微信插件
- 基于LayUI开发的 网站后台管理模板 BeginnerAdmin
- 响应式后台网站模板 - AMA.ADMIN
- layuiAdmin后台管理模板 Iframe版
- LayUI 1.0.9 升级 至 LayUI 2.1.4 方法
- 简洁清爽的会员中心模板
- jQuery幸运大转盘抽奖活动代码