Answer the question
In order to leave comments, you need to log in
Is the class written correctly to work with the database?
Actually the class itself:
class DB {
private $dbprefix;
private $mysqli;
private $connect = true;
function __construct() {
$config = new Config();
$this->dbprefix = $config->dbprefix;
if ($this->connect) {
$mysqli = new mysqli($config->host, $config->user, $config->password, $config->db);
$mysqli->set_charset("utf8");
if ($mysqli->connect_errno) {
echo "Не удалось подключиться к MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
exit();
}
$this->mysqli = $mysqli;
$this->connect = false;
}
}
public function query($data) {
$data = preg_replace('/#_/i', $this->dbprefix, $data);
return $this->mysqli->query($data);
}
public function insert_query($name, $data) {
foreach($data as $key => $val){
$field .= '`'.$this->result()->real_escape_string($key).'`, ';
if (is_numeric($val)) {
$value .=' '.$this->result()->real_escape_string($val).', ';
} else {
$value .=' \''.$this->result()->real_escape_string($val).'\', ';
}
}
$name = preg_replace('/#_/i', $this->dbprefix, $name);
$name = $this->result()->real_escape_string($name);
$this->mysqli->query('INSERT INTO `'.$name.'` ('.rtrim($field, ', ').') VALUES ('.rtrim($value, ', ').')');
return $this->mysqli->insert_id;
}
public function result() {
return $this->mysqli;
}
}
Answer the question
In order to leave comments, you need to log in
1. dbprefix is an antipattern imho.
2. config would be nice to somehow explicitly receive
3. in case of errors, it is worth throwing an exception
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question