api/Core/Model.php

104 lines
3.0 KiB
PHP
Raw Normal View History

2019-03-30 12:19:46 +00:00
<?php
namespace Core;
use PDO;
use App\Config;
/**
* Base model
*
* PHP version 7.0
*/
abstract class Model
{
public $tableName;
public $columns = array();
public $columnsType = array();
//获得一个表的所有列名
function __construct(){
$this->getColumns($this->tableName);
}
public function getColumns($tableName) {
$db = static::getDB();
$sql = "show columns from ".$tableName;
$stmt = $db->query($sql);
$res = $stmt->fetchAll();
if(static::getDB()!=null){
try{
foreach ($res as $key => $value){
array_push($this->columns,$value[0]);
array_push($this->columnsType,$value[1]);
}
}catch (\PDOException $e){
echo $e->getMessage();
}
}
}
2019-03-30 12:19:46 +00:00
/**
* Get the PDO database connection
*
* @return mixed
*/
protected static function getDB()
{
2022-01-26 14:47:34 +00:00
//echo PDO::MYSQL_ATTR_SSL_KEY;
2019-08-15 13:05:13 +00:00
$ssl = array(
2022-01-26 14:47:34 +00:00
PDO::MYSQL_ATTR_SSL_KEY =>'/var/lib/mysql/client-key.pem',
PDO::MYSQL_ATTR_SSL_CERT=>'/var/lib/mysql/client-cert.pem',
PDO::MYSQL_ATTR_SSL_CA =>'/var/lib/mysql/ca.pem',
2019-08-15 13:05:13 +00:00
PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => false,
);
2019-03-30 12:19:46 +00:00
static $db = null;
2021-02-23 12:46:33 +00:00
$option=array();
2022-01-26 14:47:34 +00:00
$timeout=time() + 50;
2019-03-30 12:19:46 +00:00
if ($db === null) {
2022-01-26 14:47:34 +00:00
$dsn = 'mysql:host=117.50.176.114' . ';dbname=' . Config::DB_NAME . ';charset=utf8';
// var_dump($dsn);
2019-08-15 13:05:13 +00:00
try {
2022-01-26 14:47:34 +00:00
$db = new PDO($dsn, Config::DB_USER, Config::DB_PASSWORD,$ssl);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
2019-08-15 13:05:13 +00:00
}catch(PDOException $e) {
2022-01-26 14:47:34 +00:00
//ho $e->getMessage();
die("sql error");
2019-08-15 13:05:13 +00:00
}
2019-03-30 12:19:46 +00:00
// Throw an Exception when an error occurs
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return $db;
}
public function InsertObject($obj){
$db = static::getDB();
$query = "insert into ".$this->tableName."(";
$val = "";
$i = 0;
foreach ($obj as $Key => $value){
// 如果key里面有包含在columns里面
if(in_array($Key,$this->columns)){
$query = $query.$Key.",";
$keyIndex = array_search($Key,$this->columns);
//print_r($this->columnsType[$keyIndex]." ");
if((strstr($this->columnsType[$keyIndex],"int(")) != false){
if(is_integer($value))
$val = $val.$value.",";
else
$val = $val."0".",";
}else{
$val = $val."'".$value."',";
}
}
$i++;
}
$val = rtrim($val,",");
$query = rtrim($query,",");
$val = $val.");";
$query = $query.") values(";
$query = $query.$val;
$stmt = $db->query($query);
}
2019-03-30 12:19:46 +00:00
}