Mysql.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace daswork\db;
  3. use mysqli;
  4. class Mysql
  5. {
  6. // 数据库连接实例
  7. private static $instance = [];
  8. // 当前数据表名称(含前缀)
  9. protected $table = '';
  10. // 当前数据表名称(不含前缀)
  11. protected $name = '';
  12. // 当前数据表主键
  13. protected $pk;
  14. // 当前数据表前缀
  15. protected $prefix = '';
  16. // 查询参数
  17. protected $options = [];
  18. /**
  19. * 数据库初始化 并取得数据库类实例
  20. * @static
  21. * @access public
  22. * @param mixed $config 连接配置
  23. * @param bool|string $name 连接标识 true 强制重新连接
  24. * @return Connection
  25. * @throws Exception
  26. */
  27. public static function connect($config = [], $name = false) {
  28. if (false === $name) {
  29. $name = md5(serialize($config));
  30. }
  31. if (true === $name || !isset(self::$instance[$name])) {
  32. if (true === $name) {
  33. return self::createConnect($config['host'], $config['username'], $config['passwd'], $config['dbname']);
  34. } else {
  35. self::$instance[$name] = self::createConnect($config['host'], $config['username'], $config['passwd'], $config['dbname']);
  36. }
  37. }
  38. return self::$instance[$name];
  39. }
  40. /**
  41. * 新建连接
  42. */
  43. private static function createConnect($host, $username, $passwd, $dbname)
  44. {
  45. $mysqli = new mysqli($host, $username, $passwd, $dbname);
  46. if ($mysqli->connect_error) {
  47. throw new \Exception('Connect Error ' . $mysqli->connect_error , $mysqli->connect_errno);
  48. }
  49. $mysqli->set_charset('utf8');
  50. return $mysqli;
  51. }
  52. /**
  53. * 指定默认的数据表名(不含前缀)
  54. * @access public
  55. * @param string $name
  56. * @return $this
  57. */
  58. public function name($name)
  59. {
  60. $this->name = $name;
  61. return $this;
  62. }
  63. /**
  64. * 指定默认数据表名(含前缀)
  65. * @access public
  66. * @param string $table 表名
  67. * @return $this
  68. */
  69. public function setTable($table)
  70. {
  71. $this->table = $table;
  72. return $this;
  73. }
  74. /**
  75. * 得到当前或者指定名称的数据表
  76. * @access public
  77. * @param string $name
  78. * @return string
  79. */
  80. public function getTable($name = '')
  81. {
  82. if ($name || empty($this->table)) {
  83. $name = $name ?: $this->name;
  84. $tableName = $this->prefix;
  85. if ($name) {
  86. $tableName .= $name;
  87. }
  88. } else {
  89. $tableName = $this->table;
  90. }
  91. return $tableName;
  92. }
  93. }