Home Function Super-fast PHP MySQL Database Class

Super-fast PHP MySQL Database Class

185
0

Questa classe di database leggera è scritta con PHP e utilizza l’estensione MySQLi, utilizza istruzioni preparate per proteggere adeguatamente le tue query, senza preoccuparti degli attacchi SQL injection.

L’estensione MySQLi ha istruzioni predefinite integrate con cui puoi lavorare, questo impedirà l’iniezione SQL e impedirà l’esposizione del tuo database, alcuni sviluppatori sono confusi su come utilizzare correttamente questi metodi, quindi ho trovato questa classe di database facile da usare.

Questa classe di database è adatta ai principianti e facile da implementare, con i metodi MySQLi nativi devi scrivere 3-7 righe di codice per recuperare i dati da un database, con questa classe puoi farlo con solo 1-2 righe di codice, ed è molto più facile da capire.
Fonte

Crea un nuovo file e chiamalo db.php e aggiungi:

<?php
class db {

    protected $connection;
	protected $query;
    protected $show_errors = TRUE;
    protected $query_closed = TRUE;
	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) {
			$this->error('Failed to connect to MySQL - ' . $this->connection->connect_error);
		}
		$this->connection->set_charset($charset);
	}

    public function query($query) {
        if (!$this->query_closed) {
            $this->query->close();
        }
		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) {
				$this->error('Unable to process MySQL query (check your params) - ' . $this->query->error);
           	}
            $this->query_closed = FALSE;
			$this->query_count++;
        } else {
            $this->error('Unable to prepare MySQL statement (check your syntax) - ' . $this->connection->error);
        }
		return $this;
    }


	public function fetchAll($callback = null) {
	    $params = array();
        $row = 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;
            }
            if ($callback != null && is_callable($callback)) {
                $value = call_user_func($callback, $r);
                if ($value == 'break') break;
            } else {
                $result[] = $r;
            }
        }
        $this->query->close();
        $this->query_closed = TRUE;
		return $result;
	}

	public function fetchArray() {
	    $params = array();
        $row = 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();
        $this->query_closed = TRUE;
		return $result;
	}

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

    public function numRows() {
		$this->query->store_result();
		return $this->query->num_rows;
	}

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

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

    public function error($error) {
        if ($this->show_errors) {
            exit($error);
        }
    }

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

}
?>

Come usare
Recupera un record da un database:

$account = $db->query('SELECT * FROM accounts WHERE username = ? AND password = ?', 'test', 'test')->fetchArray();
echo $account['name'];

Oppure potresti fare:

$account = $db->query('SELECT * FROM accounts WHERE username = ? AND password = ?', array('test', 'test'))->fetchArray();
echo $account['name'];

Recupera più record da un database:

$accounts = $db->query('SELECT * FROM accounts')->fetchAll();
foreach ($accounts as $account) {
	echo $account['name'] . '<br>';
}

È possibile specificare un callback se non si desidera che i risultati vengano archiviati in un array (utile per grandi quantità di dati):

$db->query('SELECT * FROM accounts')->fetchAll(function($account) {
    echo $account['name'];
});

Se hai bisogno di interrompere il loop puoi aggiungere:

return 'break'; 

Ottieni il numero di righe:

$accounts = $db->query('SELECT * FROM accounts');
echo $accounts->numRows();

Ottieni il numero di righe interessato:

$insert = $db->query('INSERT INTO accounts (username,password,email,name) VALUES (?,?,?,?)', 'test', 'test', 'test@gmail.com', 'Test');
echo $insert->affectedRows();

Ottieni il numero totale di query:

echo $db->query_count;

Ottieni l’ultimo ID inserito:

echo $db->lastInsertID();

Chiudere il database:

$db->close();

Conclusione

La classe del database utilizza l’estensione MySQLi, questa è integrata nella versione PHP >= 5.0.0. Se utilizzi la versione PHP da 5.0.0 a 5.3.0 avrai bisogno di installare: mysqlnd.

Non c’è bisogno di preparare istruzioni usando questa classe, lo farà automaticamente per te (scrivi di meno, fai di più), le tue query saranno sicure, ricorda solo di assicurarti di eseguire l’escape del tuo output utilizzando htmlspecialchars o il tuo metodo di escape preferito.

Sei libero di utilizzare questa classe di database nei tuoi progetti.

Previous articleEducation Institute
Next articlePHP MySQL Impaginazione Successivo Precedente Esempio

LEAVE A REPLY

Please enter your comment!
Please enter your name here