php加mysql写接口_php中怎么把数据库连接写成一个接口

展开全部

我自己e69da5e6ba903231313335323631343130323136353331333264646561封装的一个

class AppConfig{

public static $dbParam = array(

'dbHost' => 'localhost',

'dbUser' => 'root',

'dbPassword' =>'',

'dbName' => '数据库名',

'dbCharset' => 'utf8',

'dbPort' => 3306,

'dbPrefix' => 'test_',

'dbPconnect' => 0,

'dbDebug' => true,

);

}

class Model {

private $version = ''; //mysql版本

private $config = array(); //数据库配置数组

private $class; //当前类名

public $tablepre = 'ts_'; //表前缀

public $db = ''; //库名

public $table = ''; //表名

private static $link; //数据库链接句柄

private $data = array(); //中间数据容器

private $condition = ''; //查询条件

private $fields = array(); //字段信息

private $sql = array(); //sql集合,调试用

public $primaryKey = 'id'; //表主键

//构造函数初始化

public function __construct($dbParam = array()) {

$this->config = (is_array($dbParam) && !empty($dbParam)) ? $dbParam : AppConfig::$dbParam;

$this->connect();

$this->init();

}

//链接数据库

private function connect() {

if($this->config['dbPconnect']) {

self::$link = @mysql_pconnect($this->config['dbHost'], $this->config['dbUser'], $this->config['dbPassword']);

}else{

self::$link = @mysql_connect($this->config['dbHost'], $this->config['dbUser'], $this->config['dbPassword'], true);

}

mysql_errno(self::$link) != 0 && $this->errdie('Could not connect Mysql: ');

$this->db= !empty($this->db) ? $this->db : $this->config['dbName'];

$serverinfo = $this->version();

if ($serverinfo > '4.1' && $this->config['dbCharset']) {

mysql_query("SET character_set_connection=".$this->config['dbCharset'].",character_set_results=".$this->config['dbCharset'].",character_set_client=binary", self::$link);

}

if ($serverinfo > '5.0') {

mysql_query("SET sql_mode=''", self::$link);

}

@mysql_select_db($this->db, self::$link) or $this->errdie('Cannot use database');

return self::$link;

}

//表基本信息初始化

protected function init() {

$this->class = get_class($this);

$this->table = !empty($this->table) ? $this->table : strtolower($this->class);

$this->table = $this->tablepre . $this->table;

return $this;

}

//设置属性值

public function __set($name, $value) {

//exit($value);

$this->data['fields'][$name] = $value;

}

//获取属性值

public function __get($name) {

if(isset($this->data['fields'][$name])) {

return($thi

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值