<?php
/**
 * Created by PhpStorm.
 * User: Steven
 * Date: 2016/12/2
 * Time: 18:39
 */
require_once __DIR__.'/../../Config/DataBaseConfig.class.php';
class DbConfig extends DataBaseConfig
{
    /*
    *执行查询操作
    */
    public function query($sql)
    {
        $rowset = array();
        try {
            $pdo = $this->conn_waice();
            $pdo->beginTransaction();
            $result = $pdo->query($sql);
            if($result){
                $rowset = $result->fetchAll(PDO::FETCH_ASSOC);
                $result->closeCursor();
                $pdo->commit();
            }
        } catch (PDOException $ex) {
            $pdo->rollBack();
        }
        return $rowset;
    }

    /**
     * 调用执行存储过程
     * @param $sql
     * @return array|null
     */
    public function procQuery($sql)
    {
        $pdo = $this->conn_waice();
        $result = $pdo->query($sql);
        $flag = 1;
        $arr = array();
        $res = null;
        do {
            $rowset = $result->fetchAll(PDO::FETCH_ASSOC);
            if ($flag > 1) { //说明返回的结果集大于1
                if (count($arr) <= 0) {
                    $arr[] = $res[0];
                    $res = $arr;
                }
                $res[] = $rowset;
            }
            if ($flag == 1) {
                $res[0] = $rowset;
            }
            $flag++;
        } while ($result->nextRowset());
        $result->closeCursor();
        if (isset($res[0][0]['errcode']))    //如果存在errcode的话
        {
            if ($res[0][0]['errcode'] != 0)    //存储过程出错
            {
                $res1['code'] = $res[0][0]['errcode'];
                $res1['info'] = $res[0][0]['errinfo'];
                return $res1;
            } else {
                //将数组的第一个元素删除（删除包含errcode的数组）
                $res2['code'] = 0;
                $res2['info'] = '执行成功';
                $res2['data'] = array_splice($res, 1);
                return $res2;
            }
        } else {
            $res3['code'] = 0;
            $res3['info'] = '执行成功';
            $res3['data'] = $res;
            return $res3;
        }
    }


    /**
     * 执行更新操作
     * @param $sql
     * @return int
     */
    public function exec($sql)
    {
        try {
            $pdo = $this->conn_waice();
            $pdo->beginTransaction();
            $result = $pdo->exec($sql);
            $pdo->commit();
        } catch (PDOException $ex) {
            $pdo->rollBack();
        }
        return $result;
    }

    /**
     * sql添加
     * @return int
     */
    public function insert($sql)
    {
        try {
            $pdo = $this->conn_waice();
            $pdo->beginTransaction();
            $result = $pdo->exec($sql);
            $id = $pdo->lastInsertId();
            $pdo->commit();
        } catch (PDOException $ex) {
            $pdo->rollBack();
        }
        if ($result) {
            $result = $id;
        }
        return $result;
    }

}