pdo.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * Created by IntelliJ IDEA.
  4. * User: iaun
  5. * Date: 2019/8/12
  6. * Time: 9:47
  7. */
  8. global $dbInfo;
  9. $dbInfo = new stdClass();
  10. $dbInfo->ip = '127.0.0.1';
  11. $dbInfo->user = 'root';
  12. $dbInfo->password = 'Skills39.';
  13. $dbInfo->db = 'sk39';
  14. $dbInfo->port = 3306;
  15. $dbInfo->config = "mysql:host=$dbInfo->ip;dbname=$dbInfo->db";
  16. function query($name, $param)
  17. {
  18. $dbInfo = $GLOBALS['dbInfo'];
  19. try {
  20. // 创建PDO对象,最后一个参数尝试使用长连接
  21. $pdo = new PDO($dbInfo->config, $dbInfo->user, $dbInfo->password, array(PDO::ATTR_PERSISTENT => true));
  22. // 设置编码格式为utf8mb4
  23. $pdo->exec('set names utf8mb4;');
  24. } catch (PDOException $e) {
  25. // -2代表连接失败
  26. return -2;
  27. }
  28. // 补齐sql语句 形式如:call test(?,?,?)
  29. $sql = "call `$name`(";
  30. for ($i = 0, $count = count($param); $i < $count; $i++) {
  31. $sql = $sql . '?';
  32. if ($i < $count - 1) {
  33. $sql = $sql . ',';
  34. }
  35. }
  36. $sql = $sql . ')';
  37. try {
  38. // 尝试准备sql语句
  39. $stmt = $pdo->prepare($sql);
  40. } catch (PDOException $e) {
  41. // -1代表sql语句无法执行
  42. return -1;
  43. }
  44. // 循环绑定参数
  45. for ($i = 1, $count = count($param); $i <= $count; $i++) {
  46. $stmt->bindParam($i, $param[$i - 1]);
  47. }
  48. try {
  49. // 尝试执行sql语句
  50. $stmt->execute();
  51. } catch (PDOException $e) {
  52. // 同执行失败,返回-1
  53. return -1;
  54. }
  55. // 定义一个结果集的数组
  56. $rowsets = array();
  57. do {
  58. // 获取一个结果集
  59. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  60. if ($rows) {
  61. // 存在,则存入$rowsets数组
  62. array_push($rowsets, $rows);
  63. }
  64. } while ($stmt->nextRowset());
  65. $rowcount = $stmt->rowCount();
  66. if (count($rowsets) == 0 && $rowcount != 0) { // update、delete有行改变,但是没有select结果
  67. return 1;
  68. } else if (count($rowsets) != 0) { // 有select结果
  69. return count($rowsets) == 1 ? $rowsets[0] : $rowsets; // 判断是一个结果还是多个结果
  70. } else { // update、delete没有行改变,或者select没有结果
  71. return 0;
  72. }
  73. }