| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <?php
- /**
- * Created by IntelliJ IDEA.
- * User: iaun
- * Date: 2019/8/12
- * Time: 9:47
- */
- global $dbInfo;
- $dbInfo = new stdClass();
- $dbInfo->ip = '127.0.0.1';
- $dbInfo->user = 'root';
- $dbInfo->password = 'Skills39.';
- $dbInfo->db = 'sk39';
- $dbInfo->port = 3306;
- $dbInfo->config = "mysql:host=$dbInfo->ip;dbname=$dbInfo->db";
- function query($name, $param)
- {
- $dbInfo = $GLOBALS['dbInfo'];
- try {
- // 创建PDO对象,最后一个参数尝试使用长连接
- $pdo = new PDO($dbInfo->config, $dbInfo->user, $dbInfo->password, array(PDO::ATTR_PERSISTENT => true));
- // 设置编码格式为utf8mb4
- $pdo->exec('set names utf8mb4;');
- } catch (PDOException $e) {
- // -2代表连接失败
- return -2;
- }
- // 补齐sql语句 形式如:call test(?,?,?)
- $sql = "call `$name`(";
- for ($i = 0, $count = count($param); $i < $count; $i++) {
- $sql = $sql . '?';
- if ($i < $count - 1) {
- $sql = $sql . ',';
- }
- }
- $sql = $sql . ')';
- try {
- // 尝试准备sql语句
- $stmt = $pdo->prepare($sql);
- } catch (PDOException $e) {
- // -1代表sql语句无法执行
- return -1;
- }
- // 循环绑定参数
- for ($i = 1, $count = count($param); $i <= $count; $i++) {
- $stmt->bindParam($i, $param[$i - 1]);
- }
- try {
- // 尝试执行sql语句
- $stmt->execute();
- } catch (PDOException $e) {
- // 同执行失败,返回-1
- return -1;
- }
- // 定义一个结果集的数组
- $rowsets = array();
- do {
- // 获取一个结果集
- $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
- if ($rows) {
- // 存在,则存入$rowsets数组
- array_push($rowsets, $rows);
- }
- } while ($stmt->nextRowset());
- $rowcount = $stmt->rowCount();
- if (count($rowsets) == 0 && $rowcount != 0) { // update、delete有行改变,但是没有select结果
- return 1;
- } else if (count($rowsets) != 0) { // 有select结果
- return count($rowsets) == 1 ? $rowsets[0] : $rowsets; // 判断是一个结果还是多个结果
- } else { // update、delete没有行改变,或者select没有结果
- return 0;
- }
- }
|