S
S
Svyatoslav Nemato2016-09-20 10:59:39
PHP
Svyatoslav Nemato, 2016-09-20 10:59:39

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;
  }
}

Ready-made solutions are not interesting, I want to study this issue on my own.
Questions:
1. Doesn't such a class create several connections to the database, and if so, how to prevent them?
2. Is this class functional written correctly? (I don’t need other functions for working with the database, everything that is needed is described above)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Entelis, 2016-09-20
@DmitriyEntelis

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 question

Ask a Question

731 491 924 answers to any question