这个轻量级数据库类是使用 PHP 编写的,并使用 MySQLi 扩展,它使用准备好的语句来正确保护查询,无需担心 SQL 注入攻击。
MySQLi 扩展具有可以使用的内置准备语句,这将防止 SQL 注入并防止数据库被公开,一些开发人员对如何正确使用这些方法感到困惑,因此我创建了这个易于使用的数据库类,该类将执行您的工作。
此数据库类是初学者友好且易于实现,使用本机 MySQLi 方法,您需要编写 3-7 行代码才能从数据库检索数据,通过此类,只需 1-2 行代码就可以执行,并且更易于理解
代码
创建一个新文件并命名它db.php并添加:
<?phpclass 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';}}?><?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'; } } ?><?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'; } } ?>
如何使用
连接到 MySQL 数据库:
include 'db.php';$dbhost = 'localhost';$dbuser = 'root';$dbpass = '';$dbname = 'example';$db = new db($dbhost, $dbuser, $dbpass, $dbname);include 'db.php'; $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = ''; $dbname = 'example'; $db = new db($dbhost, $dbuser, $dbpass, $dbname);include 'db.php'; $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = ''; $dbname = 'example'; $db = new db($dbhost, $dbuser, $dbpass, $dbname);
从数据库中获取记录:
$account = $db->query('SELECT * FROM accounts WHERE username = ? AND password = ?', array('test', 'test'))->fetchArray();echo $account['name'];$account = $db->query('SELECT * FROM accounts WHERE username = ? AND password = ?', array('test', 'test'))->fetchArray(); echo $account['name'];$account = $db->query('SELECT * FROM accounts WHERE username = ? AND password = ?', array('test', 'test'))->fetchArray(); echo $account['name'];
从数据库中获取多个记录:
$accounts = $db->query('SELECT * FROM accounts')->fetchAll();foreach ($accounts as $account) {echo $account['name'] . '<br>';}$accounts = $db->query('SELECT * FROM accounts')->fetchAll();foreach ($accounts as $account) { echo $account['name'] . '<br>';}$accounts = $db->query('SELECT * FROM accounts')->fetchAll();foreach ($accounts as $account) { echo $account['name'] . '<br>';}
如果不希望将结果存储在数组中(对大量数据有用),可以指定回调:
$db->query('SELECT * FROM accounts')->fetchAll(function($account) {echo $account['name'];});$db->query('SELECT * FROM accounts')->fetchAll(function($account) { echo $account['name'];});$db->query('SELECT * FROM accounts')->fetchAll(function($account) { echo $account['name'];});
如果需要打破循环,可以添加:
return 'break';return 'break';return 'break';
获取条数(行数):
$accounts = $db->query('SELECT * FROM accounts');echo $accounts->numRows();$accounts = $db->query('SELECT * FROM accounts'); echo $accounts->numRows();$accounts = $db->query('SELECT * FROM accounts'); echo $accounts->numRows();
获取受影响的行数:
$insert = $db->query('INSERT INTO accounts (username,password,email,name) VALUES (?,?,?,?)', 'test', 'test', 'test@gmail.com', 'Test');echo $insert->affectedRows();$insert = $db->query('INSERT INTO accounts (username,password,email,name) VALUES (?,?,?,?)', 'test', 'test', 'test@gmail.com', 'Test'); echo $insert->affectedRows();$insert = $db->query('INSERT INTO accounts (username,password,email,name) VALUES (?,?,?,?)', 'test', 'test', 'test@gmail.com', 'Test'); echo $insert->affectedRows();
获取查询总数:
echo $db->query_count;echo $db->query_count;echo $db->query_count;
获取最后一个插入 ID:
echo $db->lastInsertID();echo $db->lastInsertID();echo $db->lastInsertID();
关闭数据库:
$db->close();$db->close();$db->close();
结论
数据库类使用 MySQLi 扩展,该扩展内置于 PHP 版本 >= 5.0.0 中。如果使用 PHP 版本 5.0.0 到 5.3.0,则需要安装:mysqlnd。
无需使用此类准备语句,它会自动为您执行该操作(编写更少,执行更多操作),您的查询将是安全的,只需记住确保使用html特殊字符,或您首选的转义方法。
您可以在项目中自由使用此数据库类。
© 版权声明
THE END
暂无评论内容