การใช้งาน Super fast PHP MySQL Database Class
2022-04-08 Games 7392022-04-08 Games
1. สร้างไฟล์ db.php ( ที่มา codeshack.io)
<?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';
}
}
?>
2. ตั้งค่าและติดต่อกับ MySQL database
include 'db.php'; $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = ''; $dbname = 'example'; $db = new db($dbhost, $dbuser, $dbpass, $dbname);
3. ตัวอย่างการใช้งาน
การ query ข้อมูลรายการเดียว แบบทั่วๆไป
$account = $db->query('SELECT * FROM accounts WHERE username = ? AND password = ?', 'test', 'test')->fetchArray();
echo $account['name'];
ใช้ array มาร่วมกับการ query ข้อมูลรายการเดียว
$account = $db->query('SELECT * FROM accounts WHERE username = ? AND password = ?', array('test', 'test'))->fetchArray();
echo $account['name'];
การ query ข้อมูลหลายรายการ
$accounts = $db->query('SELECT * FROM accounts')->fetchAll();
foreach ($accounts as $account) {
echo $account['name'] . '
';
}
ใช้ callback function หากไม่ต้องการให้เก็บข้อมูลที่ query ได้ไว้ใน array
$db->query('SELECT * FROM accounts')->fetchAll(function($account) {
echo $account['name'];
});
นับจำนวนข้อมูลที่ query ได้
$accounts = $db->query('SELECT * FROM accounts');
echo $accounts->numRows();
นับจำนวนข้อมูลที่ทำการ query ผ่าน
$insert = $db->query('INSERT INTO accounts (username,password,email,name) VALUES (?,?,?,?)', 'test', 'test', 'test@gmail.com', 'Test');
echo $insert->affectedRows();
นับจำนวนครั้งที่ query ข้อมูล
echo $db->query_count;
แสดง id ล่าสุดที่ query
echo $db->lastInsertID();
ปิดการใช้ database
$db->close();
เช็คการมีอยู่ของข้อมูลก่อนทำการ insert
$num_rows = $db->query('SELECT * FROM your_table WHERE column_name = ?', $some_value)->numRows();
if (!$num_rows) {
$db->query('INSERT INTO your_table (column1,column2) VALUES (?,?)', $some_value, $some_value2);
}
insert ข้อมูลหลายชุดใน query เดียว
$db->query('INSERT INTO table (a,b) VALUES (?,?), (?,?), (?,?)', 1, 2, 2, 3, 3, 4);
การเลือกค่าที่อยู่ใน array
$ids = [1, 2, 3]; //array(1,2,3,4);
$clause = implode(',', array_fill(0, count($ids), '?'));
$accounts = $db->query('SELECT * FROM accounts WHERE id IN (' . $clause . ')', $ids)->fetchAll();
ใช้ rtrim ช่วยสร้าง ? จากข้อมูล array
$result = $db->query('DELETE FROM answers WHERE question_id IN (' . rtrim(str_repeat('?,', count($questionIds)), ',') . ') AND owner_id = ?', $questionIds, $ownerId);
ลดการเรียกใช้ query ซ้ำ
$query = $db->query('SELECT * FROM _TABLE_ WHERE id = ? ', $id);
$count = $query->numRows();
$result = $query->fetchArray();
การใช้ LIKE
$ref_unica = $db->query("SELECT SKU FROM woocommerce WHERE SKU LIKE ? ORDER BY ID Desc", $ref . '%');
การใช้ตัวแปรสำหรับ table name
$safelist = array('table1', 'table2', 'table3');
$table = 'table1';
if (in_array($table, $safelist)) {
$sql = $db->query("SELECT * FROM $table")->fetchAll();
}
จัดการข้อมูล query ใหม่ ด้วย array_column
$results = $db->query("select `id` from `users`")->fetchAll();
$ids = array_column($results, 'id');
การใช้ SELECT MAX เรียกค่ามากที่สุด
$counter = $db->query('SELECT MAX(number) FROM cms_useronline')->fetchArray();
echo $counter['MAX(number)'];
การใช้ SELECT DISTINCT นับจำนวนข้อมูลที่ต่างกัน
$useronline = $db->query('SELECT DISTINCT ip FROM cms_useronline')->fetchAll();
echo count($useronline);
คำสั่ง MySQL, PHP, MySQL | PHP
