1,新建sqliteManager管理
<?php
class ZYSqliteManager
{
}
2,设置数据库属性及创建单例
//数据库
private $db;
//单例
static private $zysqlmanger;
//判断实例初始化次数
private function __construct()
{
}
//单例初始化
/**
* @return ZYSqliteManager
*/
static public function installSql(){
// var_dump(isset(self::$zysqlmanger));
//判断实例是否初始化
if (!isset(self::$zysqlmanger)) {
self::$zysqlmanger = new self();
$sqlManager = ZYSqliteManager::installSql();
$sqlManager ->openDataBase();
}
return self::$zysqlmanger;
}
//防止被重写
private function __clone()
{
// TODO: Implement __clone() method.
}
3,打开数据库,默认在创建初始化单例时打开数据库
//打开数据库
private function openDataBase(){
$this->db = new SQLite3("/Users/xianhongzhang/Desktop/BRServiceDB.db");
if ($this->db){
}else{
echo "fail";
}
}
4,查询数据库
//查询数据库
/*
sqlstr sql语句
keysArr 字段数据
*/
public function zymanagerquery($sqlStr, $keysArr){
$searchResult = $this->db->query($sqlStr);
$arr = array();
//遍历查询结果
while ($item = $searchResult->fetchArray()){
$dataDic = array();
for ($i = 0; $i < count($keysArr); $i ++){
$key = $keysArr[$i];
$dataDic[$key] = $item[$key];
}
$arr[] = $dataDic;
};
return $arr;
}
5,添加删除修改数据库
//添加 修改 删除 数据
public function zymanagerInserUpDelData($sqlStr){
//添加数据 删除更新同样
$result = $this->db->exec($sqlStr);
return $result;
}
6,调用实例,新建一个php file作为接口类
<?php
require_once "../ZYSql/ZYSqlmanager.php";
include "response.php";
$phone = $_GET["phone"];
$password = $_GET["password"];
$resultArr = array();
header('Content-Type:application/json');//这个类型声明非常关键
if (!$phone || !$password){
$resultArr["code"] = 201;
$resultArr["message"] = "phone or password is nil";
echo json_encode($resultArr);
return;
}
$sqlManager = ZYSqliteManager::installSql();
$keysArr = ["id","name","phone","nickname","sign","addr"];
$dataArr = $sqlManager->zymanagerquery("select *from UserList",$keysArr);
$resultArr["data"] = $dataArr;
$resultArr["code"] = 200;
$resultArr["message"] = "success";
$result = json_encode($resultArr);
echo $result;
?>