config1.inc.php

$CONFIG_DATABASE_TXL = array(
#array('127.0.0.1', 'root', '', 'he_txl','3306')
array('127.0.0.1', 'aspire_txl', 'd90wBE[wc', 'he_txl', '3306')
);

DB.class.php

<?php
/**
* 数据库操作 (PDO)
*
*/ class DB { private static $mConnection = array ();
private static $mInstance = array (); private $_lastConnect = null;
private $_connection = array ();
private $_config = array (); /**
* see @BuildCondition
*/
private static $_params = array (); /**
* 获取唯一实例
*
* @param array config db config param
* @return instance of object
*/
static function Instance($config = array()) {
$key = serialize ( $config ); if (! isset ( self::$mInstance [$key] ) or empty ( self::$mInstance [$key] ) or empty ( self::$mConnection ))
self::$mInstance [$key] = new DB ( $config ); return self::$mInstance [$key];
} /**
* 构造方法
*/
private function __construct($config = array()) {
$this->_config = $config;
$this->Connect ();
} function Connect() {
if (! empty ( $this->_connection ))
return; $option = array (PDO::ATTR_EMULATE_PREPARES => true, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'" ); $config = $this->_config;
foreach ( $config as $i => $database ) {
$dsn = isset ( $database [4] ) ? "mysql:dbname={$database[3]};host={$database[0]};port={$database[4]}" : "mysql:dbname={$database[3]};host={$database[0]}";
try {
$this->_connection [$i] = new PDO ( $dsn, $database [1], $database [2], $option );
} catch ( Exception $e ) {
throw new Exception ( 'Connect ' . $dsn . ' failed: ' . $e->getMessage () );
}
}
} /**
* 析构方法
*/
function __destruct() {
$this->Close ();
} /**
* 关闭
*/
function Close() {
$this->_connection = array ();
} /**
* 获取最后插入ID
*/
function GetInsertId() {
$i = isset ( $this->_lastConnect ) ? $this->_lastConnect : 0;
return is_object ( $this->_connection [$i] ) ? ( int ) $this->_connection [$i]->lastInsertId () : false;
} /**
* get db connection
*
* @param bool $isSelect 指定db
* @return object
*/
private function _getConn($isSelect = false) {
$i = rand ( 0, count ( $this->_config ) - 1 );
$this->_lastConnect = ($isSelect && $i) ? $i : 0;
if (! is_object ( $this->_connection [$this->_lastConnect] ))
$this->Connect ();
$conn = $this->_connection [$this->_lastConnect];
return $conn;
} /**
* 组建QueryCondition
*
* @param mix $condition;
* @param string $logic, optional
* @return string $condition
*/
static function BuildCondition($condition = array(), $logic = 'AND') {
if (is_string ( $condition ) || is_null ( $condition ))
return $condition; $logic = strtoupper ( $logic );
$content = null;
foreach ( $condition as $k => $v ) {
$v_str = ' ? ';
$v_connect = '='; if (is_numeric ( $k )) {
$content .= ' ' . $logic . ' (' . self::BuildCondition ( $v ) . ')';
continue;
} $maybe_logic = strtoupper ( $k );
if (in_array ( $maybe_logic, array ('AND', 'OR' ) )) {
$content .= $logic . ' (' . self::BuildCondition ( $v, $maybe_logic ) . ')';
continue;
} if (is_numeric ( $v )) {
self::$_params [] = $v;
} else if (is_null ( $v )) {
$v_connect = ' IS ';
$v_str = 'NULL';
} else if (is_array ( $v ) && ($c = count ( $v ))) {
if (1 < $c) {
self::$_params = array_merge ( self::$_params, $v );
$v_connect = 'IN(' . join ( ',', array_fill ( 0, $c, '?' ) ) . ')';
$v_str = '';
} else if (empty ( $v )) {
$v_str = $k;
$v_connect = '<>';
} else {
$tmp_keys = array_keys ( $v );
$v_connect = array_shift ( $tmp_keys );
if (is_numeric ( $v_connect ))
$v_connect = '=';
$tmp_values = array_values ( $v );
$v_s = array_shift ( $tmp_values ); if (is_array ( $v_s )) {
$v_str = 'IN (' . join ( ',', array_fill ( 0, count ( $v_s ), '?' ) ) . ')';
self::$_params = array_merge ( self::$_params, $v_s );
} else {
self::$_params [] = $v_s;
} }
} else {
self::$_params [] = $v;
} $content .= " $logic `$k` $v_connect $v_str "; } $content = preg_replace ( '/^\s*' . $logic . '\s*/', '', $content );
$content = preg_replace ( '/\s*' . $logic . '\s*$/', '', $content );
$content = trim ( $content ); return $content;
} /**
* 根据条件获取一条记录
* @param string $table 表名
* @param mix $condition 条件
* @param array $option 查询选项
* @return record
*/
public function GetTableRow($table, $condition, $options = array()) {
return $this->LimitQuery ( $table, array ('condition' => $condition, 'one' => isset ( $options ['one'] ) ? $options ['one'] : true, 'select' => isset ( $options ['select'] ) ? $options ['select'] : '*' ) );
} /**
* 根据条件获取有限条数记录
* @param string $table 表名
* @param array $options 查询选项
$options 可以包含 cache 选单,表示记录cache时间
* @return array of record
*/
function LimitQuery($table, $options = array()) {
return $this->DBLimitQuery ( $table, $options );
} /**
* 根据条件获取有限条数记录,从库中查询,并进行缓存
*
* @param string $table 表名
* @param array $option 查询选项
* @return array of record
*/
function DBLimitQuery($table, $options = array()) {
$condition = isset ( $options ['condition'] ) ? $options ['condition'] : null;
$one = isset ( $options ['one'] ) ? $options ['one'] : false;
$offset = isset ( $options ['offset'] ) ? abs ( intval ( $options ['offset'] ) ) : 0; if ($one)
$size = 1;
else
$size = isset ( $options ['size'] ) ? abs ( intval ( $options ['size'] ) ) : null; $order = isset ( $options ['order'] ) ? $options ['order'] : null;
$select = isset ( $options ['select'] ) ? $options ['select'] : '*'; $condition = self::BuildCondition ( $condition );
$condition = (null == $condition) ? null : "WHERE $condition"; if ($one)
$limitation = " LIMIT 1 ";
else
$limitation = $size ? "LIMIT $offset,$size" : null; $sql = "SELECT $select FROM `$table` $condition $order $limitation";
return $this->GetQueryResult ( $sql, $one, self::$_params );
} /**
* 执行真正的数据库查询
* @param string $sql
* @param bool $one 是否单条记录
* @return array of $record
*/
function GetQueryResult($sql, $one = true, array $params = array()) {
$ret = array ();
$stmt = $this->Execute ( $sql, $params );
if (! is_object ( $stmt )) {
error_log ( 'Error: bad sql - ' . $sql );
error_log ( 'Error: bad sql - ' . var_export ( $params, true ) );
return array ();
} else {
return $one ? $stmt->fetch () : $stmt->fetchAll ();
}
} /**
* 插入一条记录 Alias of method: Insert
* @param string $table 表名
* @param array $condition 记录
* @return int $id
*/
function SaveTableRow($table, $condition) {
return $this->Insert ( $table, $condition );
} /**
* 插入一条记录
* @param string $table 表名
* @param array $condition 记录
* @return int $id
*/
function Insert($table, $condition, $type = 0) {
//print_r($condition);
$content = null;
$sql = "INSERT INTO `$table`
(`" . join ( '`,`', array_keys ( $condition ) ) . '`)
values (' . join ( ',', array_fill ( 0, count ( $condition ), '?' ) ) . ')'; $stmt = $this->Execute ( $sql, array_values ( $condition ) );
// Log::ImageErrorLog($sql);
if (1 == $type) { //用于不是自增id时的判断
return is_object ( $stmt );
}
$insertId = $this->GetInsertId ();
return $insertId;
} /**
* 删除一条记录 Alias of method: Delete
* @param string $table 表名
* @param array $condition 条件
* @return int $id
*/
function DelTableRow($table = null, $condition = array()) {
return $this->Delete ( $table, $condition );
} /**
* 删除一条记录
* @param string $table 表名
* @param array $condition 条件
* @return int $id
*/
function Delete($table = null, $condition = array()) {
if (null == $table || empty ( $condition ))
return false; $condition = self::BuildCondition ( $condition );
$condition = (null == $condition) ? null : "WHERE $condition";
$sql = "DELETE FROM `$table` $condition";
$flag = $this->Execute ( $sql, self::$_params );
return $flag;
} function Execute($sql, array $params = array(), $retry = 0) {
$conn = $this->_getConn ();
$sth = $conn->prepare ( $sql );
if (! is_object ( $sth ))
throw new Exception ( 'Error: bad sql' );
$sth->setFetchMode ( PDO::FETCH_ASSOC ); $result = empty ( $params ) ? $sth->execute () : $sth->execute ( array_values ( $params ) ); //pdo error info
//$arr = $sth->errorInfo();
//print_r($arr); if (($sth->errorCode () == 2006) and ! $retry) {
$this->Close ();
$this->Execute ( $sql, $params, $retry = 1 );
} self::$_params = array ();
if (false == $result) {
$this->Close ();
return false;
} return $sth;
} /**
* 更新一条记录
* @param string $table 表名
* @param mix $id 更新条件
* @param mix $updaterow 修改内容
* @param string $pkname 主键
* @return boolean
*/
function Update($table = null, $id = 1, $updaterow = array(), $pkname = 'id') {
if (null == $table || empty ( $updaterow ) || null == $id)
return false; if (is_array ( $id ))
$condition = self::BuildCondition ( $id );
else
$condition = "`$pkname`='$id'"; $sql = "UPDATE `$table` SET ";
$content = null;
$updates = array ();
$v_str = '?'; foreach ( $updaterow as $k => $v ) {
if (is_array ( $v )) {
$str = $v [0]; //for 'count'=>array('count+1');
$content .= "`$k`=$str,";
} else {
$updates [] = $v;
$content .= "`$k`=$v_str,";
}
} $content = trim ( $content, ',' );
$sql .= $content;
$sql .= " WHERE $condition";
$result = $this->Execute ( $sql, array_merge ( $updates, self::$_params ) ); return is_object ( $result ) ? $result->rowCount () : false;
} /**
* 是否存在符合条件的记录
* @param string $table 表名
* @param array $condition
* @param boolean $returnid 是否返回记录id
* @return mixed (int)id /(array)record
*/
function Exist($table, $condition = array(), $returnid = true, $order = '') {
$row = $this->LimitQuery ( $table, array ('condition' => $condition, 'one' => true, 'order' => $order ) ); if ($returnid)
return empty ( $row ) ? false : (isset ( $row ['id'] ) ? $row ['id'] : true);
else
return empty ( $row ) ? array () : $row;
} static function CheckInt(&$id, $is_abs = false) {
if (is_array ( $id )) {
foreach ( $id as $k => $o )
$id [$k] = self::CheckInt ( $o );
return $id;
} if (! is_int ( $id ))
$id = intval ( $id ); if (0 > $id && $is_abs)
return abs ( $id );
else
return $id;
} /**
* 检查是否DB用于的Array
* @param mix $arr
* @return int $arr
*/
static function CheckArray(&$arr) {
if (! is_array ( $arr )) {
if (false === $arr)
$arr = array ();
else
settype ( $arr, 'array' );
}
return $arr;
} public function Query($sql, $isSelect = false) {
$result = $this->_getConn ( $isSelect )->query ( $sql );
if ($result)
return $result; self::Close ();
return false;
}
}

getActivity.php

<?php

/**
* 多方电话h5 - 获取运营活动列表接口
*/
$action = '多方电话h5_获取运营活动列表';
include_once '../api_driver.php';
include_once 'config.php'; $st = Login::getLoginCookie('mobile');
if ($st) {
$ret = CenAuth::validate($st);
if (isset($ret['error_code']) && $ret['error_code'] == 0) {
$mobile = $ret['data']['mobile'];
} else {
$mobile = '';
}
} else {
$mobile = '';
} $db = DB::Instance($CONFIG_DATABASE_TXL);
$adv_list = $db->GetQueryResult('SELECT `title`, `url`, `image` FROM `h5dfdh` where 1=1', FALSE); foreach ($adv_list as $k => &$value) {
if ($_SERVER['HTTPS']) {
$value['image'] = IMGURL_HTTPS . $value['image'];
} else {
$value['image'] = IMGURL . $value['image'];
}
} $data = $adv_list;
json_result(0, $data, 'ok');
/*
if ($mobile) {
$data = array(array('title'=>'H5版多方通话', 'url'=>'https://txl.cytxl.com.cn/html5/multi-party-call/static/img/img-intro-advertise.f102fb3.png', 'image'=>'https://txl.cytxl.com.cn/html5/multi-party-call/static/img/img-intro-advertise.f102fb3.png'));
json_result(0, $data, 'ok');
} else {
json_result(-1, array(), '请先登录!');
}
*/

PHP mysql client封装的更多相关文章

  1. How to Allow MySQL Client to Connect to Remote MySql

    How to Allow MySQL Client to Connect to Remote MySQ By default, MySQL does not allow remote clients ...

  2. 编译pure-ftpd时提示错误Your MySQL client libraries aren't properly installed

    如果出现类似configure: error: Your MySQL client libraries aren’t properly installed 的错误,请将mysql目录下的 includ ...

  3. configure: error: Cannot find libmysqlclient under /usr Note that the MySQL client library is not bundled anymore! 报错解决

    错误说明 今天在centos 6.3 64位版本上安装PHP5.4.3时在./configure 步骤的时候出现了下面错误configure: error: Cannot find libmysqlc ...

  4. php编译错误Note that the MySQL client library is not bundled anymore或者cannot find mysql header file

    rpm -ivh MySQL-devel-community-5.1.57-1.sles10.x86_64.rpm export PATH=/usr/local/services/libxml2-2. ...

  5. Linux Mysql Client 查询中文乱码

    1.mysql client 端设置编码为utf8 set character_set_results=utf8; 2.连接linux的客户端的编码也要设置为utf8(比如xshell,putty等)

  6. php编译错误Note that the MySQL client library is not bundled anymore!

    Note that the MySQL client library is not bundled anymore! 解决方法. 1. 查看系统有没有安装mysql header find / -na ...

  7. C#工具类OracleHelper,基于Oracle.ManagedDataAccess.Client封装

    基于Oracle.ManagedDataAccess.Client封装的Oracle工具类OracleHelper,代码如下: using System; using System.Data; usi ...

  8. Reactive MySQL Client

    Reactive MySQL Client是MySQL的客户端,具有直观的API,侧重于可伸缩性和低开销. 特征 事件驱动 轻量级 内置连接池 准备好的查询缓存 游标支持 行流 RxJava 1和Rx ...

  9. egg 连接 mysql 的 docker 容器,报错:Client does not support authentication protocol requested by server; consider upgrading MySQL client

    egg 连接 mysql 的 docker 容器,报错:Client does not support authentication protocol requested by server; con ...

随机推荐

  1. Java 保存对象到文件并恢复 ObjectOutputStream/ObjectInputStream

    1.从inputFile文件中获取内容,读入到set对象: 2.然后通过ObjectOutputStream将该对象保存到outputFile文件中: 3.最后通过ObjectInputStream从 ...

  2. TOF 初探

    TOF 简介 TOF是Time of flight的简写,直译为飞行时间的意思.所谓飞行时间法3D成像,是通过给目标连续发送光脉冲,然后用传感器接收从物体返回的光,通过探测光脉冲的飞行(往返)时间来得 ...

  3. BZOJ5280: [Usaco2018 Open]Milking Order(二分+拓扑)

    5280: [Usaco2018 Open]Milking Order Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 123  Solved: 62[ ...

  4. BZOJ4837:[Lydsy1704月赛]LRU算法(双指针&模拟)

    Description 小Q同学在学习操作系统中内存管理的一种页面置换算法,LRU(LeastRecentlyUsed)算法. 为了帮助小Q同学理解这种算法,你需要在这道题中实现这种算法,接下来简要地 ...

  5. 通过以太坊发行代币(token)

    2017年开始,区块链ICO项目层出不穷,市场热度一波更胜一波,很多ICO都是通过以太坊智能合约发行自己的代币(token),具体怎样才能发行代币呢?本文进行具体详细的介绍. 准备工作 以太坊官网ER ...

  6. psoc4的中断笔记

    psoc可以自定义中断服务函数.

  7. chrome扩展程序开发之在目标页面执行自己的JS

    大家都知道JS是执行在client的.所以,假设我们自己写一个浏览器的话.是一定能够往下载下来的网页源码中加入js的.可惜我们没有这个能力.只是幸运的是,chrome的扩展程序能够帮我们做到这件事. ...

  8. [Oracle] CPU/PSU补丁安装详细教程

    Oracle CPU的全称是Critical Patch Update, Oracle对于其产品每个季度发行一次安全补丁包,通常是为了修复产品中的安全隐患,以下是对CPU/PSU补丁安装的具体操作步骤 ...

  9. YARN的Fair Scheduler和Capacity Scheduler

    关于Scheduler YARN有四种调度机制:Fair Schedule,Capacity Schedule,FIFO以及Priority: 其中Fair Scheduler是资源池机制,进入到里面 ...

  10. Windows运行命令集锦

    开始菜单中的“运行”(Win+R)是通向程序的快捷途径,输入特定的命令后,即可快速的打开Windows的大部分程序,熟练的运用它,将给我们的操作带来诸多便捷. winver 检查Windows版本  ...