api/Core/Model.php

106 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()
{
$ssl = array(
PDO::MYSQL_ATTR_SSL_KEY =>'D:\\data\\腾讯云测试服mysql证书\\client-key.pem',
PDO::MYSQL_ATTR_SSL_CERT=>'D:\\data\\腾讯云测试服mysql证书\\client-cert.pem',
PDO::MYSQL_ATTR_SSL_CA =>'D:\\data\\腾讯云测试服mysql证书\\ca.pem',
PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => false,
);
static $db = null;
$option=array();
$timeout=time() + 20;
if ($db === null) {
$dsn = 'mysql:host=' . Config::DBUrl() . ';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) {
//echo $e->getMessage();
die;
}
// 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);
var_dump($stmt);
print_r($stmt->errorInfo());
//$res = $stmt->fetch();
//$result = $stmt->fetchAll();
//return $res;
}
}