Вход Регистрация
* Gooden

Работаем с базой данных - урок 1

  1. class DBLite {
  2.  
  3. // Текущая версия вашего mysqli
  4. public $info = '';
  5.  
  6. // Настройки для подключения и выбора базы данной
  7. protected $data = array('server' => 'database', 'username' => 'root', 'password' => '','database' => '', 'prefix' => 'table', 'charset' => 'utf8', 'collate' => 'utf8_general_ci');
  8.  
  9. //Результат подключения к серверу
  10. public $connect = false;
  11.  
  12. //Результат выполняемого запроса
  13. protected $query = false;
  14.  
  15. // Мониторинг запросов базы данной
  16. public $monitor = array('time' => 0, 'count' => 0);
  17.  
  18. /**
  19.   * Запускаем наш гребаный велосипед
  20.   */
  21. public function __construct ($conf) {
  22. foreach ($conf as $key => $value) {
  23. if ($value == null) continue;
  24. $this->data[$key] = $value;
  25. }
  26. $this->__connect();
  27. }
  28.  
  29. /**
  30.   * Подключаемся к серверу базы данной
  31.   */
  32. protected function __connect () {
  33. $this->connect = @mysqli_connect($this->data['server'], $this->data['username'], $this->data['password'], $this->data['database']);
  34. if (!$this->connect)
  35. exit('Не удалось подключиться к серверу: '.mysqli_connect_error());
  36. $this->info = mysqli_get_server_info($this->connect);
  37. if (version_compare($this->info, '5.0', 'lt'))
  38. exit ('Для работы требуется MySQLi 5.0 либо выше');
  39. mysqli_query($this->connect, 'SET NAMES "'.$this->data['charset'].'" COLLATE "'.$this->data['collate'].'"');
  40. return $this->connect;
  41. }
  42.  
  43. /**
  44.   * Устанавливаем префикс к имени таблице
  45.   */
  46. protected function prefix ($query) {
  47. return trim(str_replace('@', $this->data['prefix'].'_', $query));
  48. }
  49.  
  50. /**
  51.   * Выполняем запрос в базу
  52.   */
  53. public function query ($query) {
  54. $start_time = microtime(true);
  55. $this->query = @mysqli_query($this->connect, $this->prefix($query));
  56. if (mysqli_error($this->connect)) {
  57. Cache::write('dblite.log', mysqli_error($this->connect));
  58. }
  59. $this->monitor['count']++;
  60. $end_time = microtime(true) - $start_time;
  61. $this->monitor['time'] += $end_time;
  62. return $this->query;
  63. }
  64.  
  65. /**
  66.   * Выполняем реальный запрос
  67.   */
  68. public function real_query ($query, $real = false) {
  69. $this->query($query);
  70. if ($real) {
  71. $content = array();
  72. while ($while = $this->real_fetch())
  73. $content[] = $while;
  74. return $content;
  75. } else {
  76. $content = $this->real_fetch();
  77. return $content;
  78. }
  79. }
  80.  
  81. /**
  82.   * Получаем количества данные результата запроса
  83.   */
  84. public function real_result ($query) {
  85. $result = mysqli_fetch_row($this->query($query));
  86. return $result[0];
  87. }
  88.  
  89. /**
  90.   * Обрабатываем результат запроса
  91.   */
  92. public function real_fetch ($query = false) {
  93. if (!$query) $query = $this->query;
  94. return mysqli_fetch_assoc($query);
  95. }
  96.  
  97. /**
  98.   * Id следующего результата запроса
  99.   */
  100. public function real_next_id () {
  101. return mysqli_insert_id($this->connect);
  102. }
  103.  
  104. /**
  105.   * Обработка текста при выполнении запроса
  106.   */
  107. public function real_safe ($text) {
  108. return mysqli_real_escape_string($this->connect, $text);
  109. }
  110.  
  111. /**
  112.   * Освобождаем память от результата запроса
  113.   */
  114. public function real_free ($query = false) {
  115. if (!$query) $query = $this->query;
  116. return mysqli_free_result($query);
  117. }
  118.  
  119. /**
  120.   * При завершении работы класса подключение с MySQLi автоматически закрываем
  121.   */
  122. public function __destruct() {
  123. if ($this->connect) {
  124. mysqli_close($this->connect);
  125. }
  126. }
  127.  
  128. }
» Описание: Подключение идет через mysqli, читайте не забудьте поставить класс)) Как применять его смотрите мой следующий урок.
» Время добавления: 24 Июня 2015 в 10:20
» Посмотров: 1780
» textarea
» Рейтинг: [+0 | -0]
Комментарии [0]
Онлайн: 1
Реклама