Another module for working with MySQL

    There was not enough karma to put on a specialized blog. But it is very interesting to discuss.
    Tired of routine operations when working with the database. I decided to somehow rectify the situation. I spent about half an hour looking at existing classes, I didn’t find anything suitable for myself. And he decided that it would be easier to write your own.

    Actually, what I wanted to get:
    1. Save your memory.
    For work, you have to maintain and write sites on 4-5 server platforms in different countries. Passwords and (rarely but still) network addresses are constantly changing. Therefore, I wanted to somehow centralize the connection settings and save myself from the need to remember dozens of addresses and passwords, but simply scatter one file across all servers and, if necessary, just use the database server we needed.

    2. Save your time.
    I am lazy. I quickly get tired of pieces of code that I have to carry with me from script to script. I wanted to give a request and get an array.

    3. I wanted freedom.
    Many modules that caught my eye for a short search time, tried to organize queries themselves.
    Of course, this might seem more convenient to someone than writing queries yourself, but often you have to use complex queries and spend time analyzing how to write all this so that the “smart” module turns it all into a correct and optimal query.

    Actually, this is what happened. The server name is made just in case. every case happened when it was required that the script work differently depending on which north it is connected to.
    class db {
    private static $flag_one; // флаг сингельтона
    //пораметры подключения по умолчанию
    private $host = 'localhost';
    private $user = 'root';
    private $password;
    private $database = 'mydb';

    private $connect; //хранитель коннекта с базой
    private $result; //хранитель коннекта результата запроса
    private $server; //имя сервера
    public $query_log_mask = 'query%.log'; //маска файла логов
    public $debug=0; // включить/выключить логирование всех запросов


    Both the log mask and debug flag are available for changing during the script, which is sometimes very useful.

    I think it does not need comments. In the contract, I decided to define all the servers and specific parameters for connecting to them. It also establishes a connection to the database and sets the encoding. We prohibit duplication; close the connection to the database before deleting the class from memory. Functions for getting the server and database name. Actually the heart of the whole module)) A function that makes a request to the database, and if necessary logs it. The request processing function accepts the request (or uses the result of the last executed one) and returns the array Function to get the number of rows in the request:
    public static function one($server = 'local'){
    if (!isset(self::$flag_one)) {
    $c = __CLASS__;
    self::$flag_one = new $c($server);
    }
    return self::$flag_one;
    }




    protected function __construct($server) {
    $this->server=$server;
    switch ($server) {
    case 'server1':
    $this->password = 'abcde';
    break;
    case 'server2':
    $this->host='192.168.0.100';
    $this->user='someuser';
    $this->database='somedb';
    $this->password = 'edcba';
    break;
    default:
    $this->password = '';
    break;
    }
    $this->connect = mysql_connect($this->host, $this->user, $this->password) or die(mysql_error());
    mysql_select_db($this->database, $this->connect);
    $this->query('SET CHARSET cp1251;');
    }



    public function __clone(){
    trigger_error('Clone is not allowed.', E_USER_ERROR);
    }


    public function close() {
    mysql_close($this->connect);
    }
    public function __destruct(){
    $this->close();
    }



    public function show_server() {
    return $this->server;
    }
    public function show_db() {
    return $this->database;
    }




    public function query($query) {
    if(this->debug>0) $this->mysql_query_log($query,'debug');
    $this->result = mysql_query($query, $this->connect) or $this->mysql_query_log($query);
    }



    public function fetch_rows($query = '', $assoc = MYSQL_ASSOC) {
    if (!empty($query)) $this->query($query);
    $return = array();
    mysql_data_seek($this->result, 0);
    while($line = mysql_fetch_array($this->result, $assoc)){
    $return[] = $line;
    }
    return $return;
    }



    public function num_rows($query = '') {
    if (!empty($query)) $this->query($query);
    return mysql_num_rows($this->result);
    }


    The most dubious part. The function does an INSERT and returns the id of the inserted record.
    The question is whether it returns Id. We replace forbidden characters. The function of logging requests, erroneous (or all). You can download the module here. If anyone is interested, I can give you a couple of examples of use. I'd love to hear comments and suggestions for improvement. I ask not to judge strictly, because this is my first post on Habré.
    public function insert($query = '') {
    if (!empty($query)){
    $this->query($query);
    return mysql_insert_id();
    }
    return -1;
    }



    public function add_slashes($value) {
    return mysql_real_escape_string($value, $this->connect);
    }



    private function mysql_query_log($query = '',$type='error') {
    $out='';
    $error=($type=='error');
    if (!empty($query)) {
    $out.="#---------------------------------------\r\n";
    $out.=$query."\r\n";
    if($error){
    $out.=mysql_errno($this->connect).': '.mysql_error($this->connect)."\r\n";
    $out.=var_export(debug_backtrace(), true)."\r\n";
    }
    $out.="#---------------------------------------\r\n";
    }
    $file = fopen(sprintf($this->query_log_mask,$type), 'a+');
    fwrite($file,$out);
    fclose($file);
    if($error) die('Wrong database query.');
    }
    }
    ?>







    Also popular now: