📜 ⬆️ ⬇️

Another module for working with MySQL

Not enough karma to post to a specialized blog. But it is very interesting to discuss.
Tired of routine operations when working with the database. I decided to somehow fix the situation. I spent about half an hour on viewing existing classes, I did not find anything suitable for myself. And I decided that it would be easier to write my own.

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

2. Save your time.
I'm lazy. I am quickly tired of pieces of code that I have to carry with me from the script to the script. I wanted to give a request and get an array.
')
3. I wanted freedom.
Many modules that caught my eye in the short time of the search, tried to organize the queries themselves.
Of course, it might have seemed more convenient to someone than writing the queries himself, but often you have to use complex queries and spend time analyzing how to write all this in order for the “smart” module to turn it all into a correct and optimal query.

Actually that's what happened.
<?php
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; // /

The server name is made just in case. just in case there was a need for the script to work differently depending on which north it is connected to.
Both the mask of logs and the debug flag are available for changing during the script, which is sometimes very useful.

I think does not need comments.
public static function one($server = 'local'){
if (!isset(self::$flag_one)) {
$c = __CLASS__;
self::$flag_one = new $c($server);
}
return self::$flag_one;
}


In the design, I decided to define all servers and specific parameters for connecting to them.
A connection to the database is also established and the encoding is set.
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;');
}


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

close the connection to the database before removing the class from memory.
public function close() {
mysql_close($this->connect);
}
public function __destruct(){
$this->close();
}


Functions to get the server name and database.
public function show_server() {
return $this->server;
}
public function show_db() {
return $this->database;
}


Actually the heart of the whole module))
The function that makes the query to the database, and if necessary, logs it.
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);
}


The request processing function accepts the request (or uses the result of the last executed one) and returns an array
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;
}


The function to get the number of rows in the query:
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.
Doubt is the question whether Id she returns
public function insert($query = '') {
if (!empty($query)){
$this->query($query);
return mysql_insert_id();
}
return -1;
}


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


The function of logging queries, erroneous (or all)
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.');
}
}
?>


You can download the module here.

If anyone is interested, I can give a couple of examples of use.
I'd love to hear comments and suggestions for improvement.
Please do not judge strictly, because this is my first post on Habré.

Source: https://habr.com/ru/post/56737/


All Articles