Jumast
@Jumast
разработка сайтов - html/css/php/js

Насколько крутой php mysqli класс?

Всем привет!

На просторах нашел db class насколько он хорош для разработки сайта? на PHP7.3.* без использования PDO.
Класс мне понравился без лишних наворотов, к тому же защищен от sql инъекций.
Вот класс:
<?php
class db {

    protected $connection;
	protected $query;
	public $query_count = 0;
	
	public function __construct($dbhost = 'localhost', $dbuser = 'root', $dbpass = '', $dbname = '', $charset = 'utf8') {
		$this->connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
		if ($this->connection->connect_error) {
			die('Failed to connect to MySQL - ' . $this->connection->connect_error);
		}
		$this->connection->set_charset($charset);
	}
	
    public function query($query) {
		if ($this->query = $this->connection->prepare($query)) {
            if (func_num_args() > 1) {
                $x = func_get_args();
                $args = array_slice($x, 1);
				$types = '';
                $args_ref = array();
                foreach ($args as $k => &$arg) {
					if (is_array($args[$k])) {
						foreach ($args[$k] as $j => &$a) {
							$types .= $this->_gettype($args[$k][$j]);
							$args_ref[] = &$a;
						}
					} else {
	                	$types .= $this->_gettype($args[$k]);
	                    $args_ref[] = &$arg;
					}
                }
				array_unshift($args_ref, $types);
                call_user_func_array(array($this->query, 'bind_param'), $args_ref);
            }
            $this->query->execute();
           	if ($this->query->errno) {
				die('Unable to process MySQL query (check your params) - ' . $this->query->error);
           	}
			$this->query_count++;
        } else {
            die('Unable to prepare statement (check your syntax) - ' . $this->connection->error);
        }
		return $this;
    }

	public function fetchAll() {
	    $params = array();
	    $meta = $this->query->result_metadata();
	    while ($field = $meta->fetch_field()) {
	        $params[] = &$row[$field->name];
	    }
	    call_user_func_array(array($this->query, 'bind_result'), $params);
        $result = array();
        while ($this->query->fetch()) {
            $r = array();
            foreach ($row as $key => $val) {
                $r[$key] = $val;
            }
            $result[] = $r;
        }
        $this->query->close();
		return $result;
	}

	public function fetchArray() {
	    $params = array();
	    $meta = $this->query->result_metadata();
	    while ($field = $meta->fetch_field()) {
	        $params[] = &$row[$field->name];
	    }
	    call_user_func_array(array($this->query, 'bind_result'), $params);
        $result = array();
		while ($this->query->fetch()) {
			foreach ($row as $key => $val) {
				$result[$key] = $val;
			}
		}
        $this->query->close();
		return $result;
	}
	
	public function numRows() {
		$this->query->store_result();
		return $this->query->num_rows;
	}

	public function close() {
		return $this->connection->close();
	}

	public function affectedRows() {
		return $this->query->affected_rows;
	}

	private function _gettype($var) {
	    if(is_string($var)) return 's';
	    if(is_float($var)) return 'd';
	    if(is_int($var)) return 'i';
	    return 'b';
	}

}
?>


Ссылка на сам класс: SuperFast DB CLASS
  • Вопрос задан
  • 187 просмотров
Пригласить эксперта
Ответы на вопрос 3
SerafimArts
@SerafimArts
Senior Notepad Reader
Говно.
1) Я не буду говорить про кодстайл, благо он фиксится одним сочетанием клавиш...
2) Побочные эффекты (die)
3) Куча лишних вложенностей (if if if if)
4) Полностью нарушен принцип open/close (расширяться через наследование? Серьёзно?)
5) Куча избыточного кода. Например:
call_user_func_array(array($this->query, 'bind_result'), $params);

Легко переписывается как:
$this->query->bind_result(...$params);
6) Ну и состояние, и его мутабельность, которой не должно быть, конечно же.

На помойку, короче.
Ответ написан
xmoonlight
@xmoonlight
https://sitecoder.blogspot.com
Пойдёт!
этот - тоже крутой скрипт)
Ответ написан
profesor08
@profesor08 Куратор тега PHP
Справится с таким запросом? Если да, то молодец, оформи класс и приведи в порядок, и тогда можно его показывать.
SELECT * FROM account;
SELECT * FROM cart;
SELECT * FROM favorites;
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы