sqlite在php中是默认安装的本地小型化数据库,类似于xml的小型数据库,但sqlite功能更强。
<?php class sqliteDB{ private $sqliteResult; private $error = ''; private $createTable = <<<TABLE /*初始化创建数据表,可创建多个表*/ CREATE TABLE COMPANY (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, DDRESS CHAR(50), SALARY REAL); /*初始化插入数据,可插入多个数据*/ INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 ); TABLE; function __construct($fileName){ //如果有数据库,则打开数据库 //如果没有数据库,则创建数据库,并且生成数据表及插入数据 if(file_exists($fileName)){ $this->sqliteResult = new MyDB($fileName); if(!$this->sqliteResult){ die("Database error:" . $this->sqliteResult->lastErrorMsg()); } }else{ $this->sqliteResult = new MyDB($fileName); if(!$this->sqliteResult){ die("Database error:" . $this->sqliteResult->lastErrorMsg()); } $this->execute($this->createTable); } } //此方法用于“增、删、改” function execute($sql){ $this->error= $this->sqliteResult->exec($sql); } //此方法用于“查” function queryDB($sql){ $result = $this->sqliteResult->query($sql); $i = 0; while($row = $result->fetchArray(SQLITE3_ASSOC) ){ $arr[$i] = $row; $i += 1; } return $arr; } function __destruct(){ if(!$this->error){ die("Database error:" . $this->sqliteResult->lastErrorMsg()); } $this->sqliteResult->close(); } } class MyDB extends SQLite3{ function __construct($fileName){ $this->open($fileName); } }
index.php文件:
<?php include_once("sqlite.class.php"); $sqliteInsert =<<< EOF INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Teddy', 23, 'Norway', 20000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 ); EOF; $sqliteDelete =<<< EOF DELETE from COMPANY where ID=2; EOF; $sqlUpdata =<<< EOF UPDATE COMPANY set SALARY = 28666.00 where ID=1; EOF; $sqlSelect =<<<EOF SELECT * from COMPANY; EOF; $db = new sqliteDB("test.db"); /* * $db = new sqliteDB(':memory:'); * 如果文件名赋值为':memory:',那么 SQLite3::open() 将会在 * RAM 中创建一个内存数据库,这只会在 session 的有效时间内持续。 */ foreach($db->queryDB($sqlSelect) as $value){ if($value["ID"] == 3 OR $value["ID"]== 4){ $isNull = true; } } if(!$isNull){ //增加数据 $db->execute($sqliteInsert); } //删除数据 $db->execute($sqliteDelete); //修改数据 $db->execute($sqlUpdata); echo "<pre>"; //查询数据 print_r($db->queryDB($sqlSelect)); echo "</pre>";
以上内容希望帮助到大家
扫码二维码 获取免费视频学习资料
- 本文固定链接: http://phpxs.com/post/7155/
- 转载请注明:转载必须在正文中标注并保留原文链接
- 扫码: 扫上方二维码获取免费视频资料
查 看2022高级编程视频教程免费获取