107 lines
3.2 KiB
PHP
107 lines
3.2 KiB
PHP
<?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();
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get the PDO database connection
|
|
*
|
|
* @return mixed
|
|
*/
|
|
protected static function getDB()
|
|
{
|
|
//echo PDO::MYSQL_ATTR_SSL_KEY;
|
|
$ssl = array(
|
|
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',
|
|
PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => false,
|
|
);
|
|
static $db = null;
|
|
$option=array();
|
|
$timeout=time() + 50;
|
|
|
|
if ($db === null) {
|
|
$dsn = "";
|
|
if($_SERVER['HTTP_HOST'] == '127.0.0.1')
|
|
$dsn = 'mysql:host=117.50.187.222' . ';dbname=' . Config::DB_NAME . ';charset=utf8';
|
|
else
|
|
$dsn = 'mysql:host=127.0.0.1' . ';dbname=' . Config::DB_NAME . ';charset=utf8';
|
|
try {
|
|
$db = new PDO($dsn, Config::DB_USER, Config::DB_PASSWORD,$ssl);
|
|
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
|
}catch(PDOException $e) {
|
|
//ho $e->getMessage();
|
|
die("sql error");
|
|
}
|
|
// 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);
|
|
}
|
|
}
|