PHP MySQLi 封裝類完整版(漢化使用說明)
安裝
要使用此類,首先將MysqliDb.php匯入到專案中。
require_once ('MysqliDb.php');
使用 composer 安裝
composer require joshcam/mysqli-database-class:dev-master
初始化
使用utf8編碼進行簡單初始化預設設定:
$db = new MysqliDb ('host', 'username', 'password', 'databaseName');
高階初始化:
$db = new MysqliDb (Array ( 'host' => 'host', 'username' => 'username', 'password' => 'password', 'db'=> 'databaseName', 'port' => 3306, 'prefix' => 'my_', 'charset' => 'utf8'));
表字首,埠和資料庫字符集引數是可選的。 如果不設定字符集,則將其設定為null
也可以重用已連線的mysqli物件:
$mysqli = new mysqli ('host', 'username', 'password', 'databaseName');
$db = new MysqliDb ($mysqli);
如果在建立物件期間沒有設定表字首,則可以稍後通過單獨的呼叫進行設定:
$db->setPrefix ('my_');
如果您需要從其他類或函式中使用已經建立的mysqliDb物件
function init () { // db staying private here $db = new MysqliDb ('host', 'username', 'password', 'databaseName'); } ... function myfunc () { // obtain db object created in init () $db = MysqliDb::getInstance(); ... }
物件對映
dbObject.php是建立在mysqliDb之上的物件對映庫,用於提供模型表示功能。dbObject手冊瞭解更多資訊
插入查詢
簡單例子
$data = Array ("login" => "admin",
"firstName" => "John",
"lastName" => 'Doe'
);
$id = $db->insert ('users', $data);
if($id)
echo 'user was created. Id=' . $id;
插入功能使用
$data = Array ( 'login' => 'admin', 'active' => true, 'firstName' => 'John', 'lastName' => 'Doe', 'password' => $db->func('SHA1(?)',Array ("secretpassword+salt")), // password = SHA1('secretpassword+salt') 'createdAt' => $db->now(), // createdAt = NOW() 'expires' => $db->now('+1Y') // expires = NOW() + interval 1 year // Supported intervals [s]econd, [m]inute, [h]hour, [d]day, [M]onth, [Y]ear ); $id = $db->insert ('users', $data); if ($id) echo 'user was created. Id=' . $id; else echo 'insert failed: ' . $db->getLastError();
插入與重複金鑰更新
$data = Array ("login" => "admin",
"firstName" => "John",
"lastName" => 'Doe',
"createdAt" => $db->now(),
"updatedAt" => $db->now(),
);
$updateColumns = Array ("updatedAt");
$lastInsertId = "id";
$db->onDuplicate($updateColumns, $lastInsertId);
$id = $db->insert ('users', $data);
一次插入多個數據集
$data = Array(
Array ("login" => "admin",
"firstName" => "John",
"lastName" => 'Doe'
),
Array ("login" => "other",
"firstName" => "Another",
"lastName" => 'User',
"password" => "very_cool_hash"
)
);
$ids = $db->insertMulti('users', $data);
if(!$ids) {
echo 'insert failed: ' . $db->getLastError();
} else {
echo 'new users inserted with following id\'s: ' . implode(', ', $ids);
}
如果所有資料集只有相同的鍵,可以簡化
$data = Array(
Array ("admin", "John", "Doe"),
Array ("other", "Another", "User")
);
$keys = Array("login", "firstName", "lastName");
$ids = $db->insertMulti('users', $data, $keys);
if(!$ids) {
echo 'insert failed: ' . $db->getLastError();
} else {
echo 'new users inserted with following id\'s: ' . implode(', ', $ids);
}
替換查詢
Replace() 方法實現與insert() 相同的API;
更新查詢
$data = Array (
'firstName' => 'Bobby',
'lastName' => 'Tables',
'editCount' => $db->inc(2),
// editCount = editCount + 2;
'active' => $db->not()
// active = !active;
);
$db->where ('id', 1);
if ($db->update ('users', $data))
echo $db->count . ' records were updated';
else
echo 'update failed: ' . $db->getLastError();
update() 也支援limit引數:
$db->update ('users', $data, 10);
// Gives: UPDATE users SET ... LIMIT 10
選擇查詢
在任何select / get函式呼叫之後,$count或者返回的行儲存在$count變數中
$users = $db->get('users'); //contains an Array of all users
$users = $db->get('users', 10); //contains an Array 10 users
或選擇自定義列集。功能也可以使用
$cols = Array ("id", "name", "email");
$users = $db->get ("users", null, $cols);
if ($db->count > 0)
foreach ($users as $user) {
print_r ($user);
}
或選擇一行
$db->where ("id", 1);
$user = $db->getOne ("users");
echo $user['id'];
$stats = $db->getOne ("users", "sum(id), count(*) as cnt");
echo "total ".$stats['cnt']. "users found";
或選擇一個列值或函式結果
$count = $db->getValue ("users", "count(*)");
echo "{$count} users found";
從多行中選擇一個列值或函式結果:
$logins = $db->getValue ("users", "login", null);
// select login from users
$logins = $db->getValue ("users", "login", 5);
// select login from users limit 5
foreach ($logins as $login)
echo $login;
###插入資料您還可以將.CSV或.XML資料載入到特定的表中。要插入.csv資料,請使用以下語法:
$path_to_file = "/home/john/file.csv";
$db->loadData("users", $path_to_file);
這將在 /home/john/(john的主目錄)資料夾中載入一個名為file.csv的.csv檔案。您還可以附加可選的選項陣列。有效的選項有:
Array(
"fieldChar" => ';', // Char which separates the data
"lineChar" => '\r\n', // Char which separates the lines
"linesToIgnore" => 1 // Amount of lines to ignore at the beginning of the import
);
使用它們
$options = Array("fieldChar" => ';', "lineChar" => '\r\n', "linesToIgnore" => 1);
$db->loadData("users", "/home/john/file.csv", $options);
###插入XML要將XML資料載入到表中,可以使用loadXML方法。 語法是smarse到loadData語法。
$path_to_file = "/home/john/file.xml";
$db->loadXML("users", $path_to_file);
您還可以新增可選引數。有效引數:
Array(
"linesToIgnore" => 0, // Amount of lines / rows to ignore at the beginning of the import
"rowTag" => "" // The tag which marks the beginning of an entry
)
用法:
$options = Array("linesToIgnore" => 0, "rowTag" => ""):
$path_to_file = "/home/john/file.xml";
$db->loadXML("users", $path_to_file, $options);
### Pagination使用paginate() 而不是get() 來獲取分頁結果
$page = 1;
// set page limit to 2 results per page. 20 by default
$db->pageLimit = 2;
$products = $db->arraybuilder()->paginate("products", $page);
echo "showing $page out of " . $db->totalPages;
結果轉換/地圖
而不是得到一個純陣列的結果,可能會得到一個關聯陣列與一個所需的關鍵。 如果在get() 中只能設定2個欄位來獲取,那麼在其餘的情況下,方法會在array($k => $v)和array($k => array($v,$v)) 中返回結果。
$user = $db->map ('login')->ObjectBuilder()->getOne ('users', 'login, id');
Array
(
[user1] => 1
)
$user = $db->map ('login')->ObjectBuilder()->getOne ('users', 'id,login,createdAt');
Array
(
[user1] => stdClass Object
(
[id] => 1
[login] => user1
[createdAt] => 2015-10-22 22:27:53
)
)
定義返回型別
MysqliDb可以返回3種不同格式的結果:Array陣列,物件陣列和Json字串。 選擇一個返回型別使用ArrayBuilder(),ObjectBuilder() 和JsonBuilder() 方法。 請注意,ArrayBuilder() 是預設的返回型別
// Array return type
$= $db->getOne("users");
echo $u['login'];
// Object return type
$u = $db->ObjectBuilder()->getOne("users");
echo $u->login;
// Json return type
$json = $db->JsonBuilder()->getOne("users");
執行SQL查詢
$users = $db->rawQuery('SELECT * from users where id >= ?', Array (10));
foreach ($users as $user) {
print_r ($user);
}
為了避免長時間,如果檢查有幾個幫助函式使用原始查詢選擇結果:
獲取1行結果:
$user = $db->rawQueryOne ('select * from users where id=?', Array(10));
echo $user['login'];
// Object return type
$user = $db->ObjectBuilder()->rawQueryOne ('select * from users where id=?', Array(10));
echo $user->login;
獲取1列值作為字串:
$password = $db->rawQueryValue ('select password from users where id=? limit 1', Array(10));
echo "Password is {$password}";
NOTE: for a rawQueryValue() to return string instead of an array 'limit 1' should be added to the end of the query.
從多行獲取1列值:
$logins = $db->rawQueryValue ('select login from users limit 10');
foreach ($logins as $login)
echo $login;
高階例子:
$params = Array(1, 'admin');
$users = $db->rawQuery("SELECT id, firstName, lastName FROM users WHERE id = ? AND login = ?", $params);
print_r($users); // contains Array of returned rows
// will handle any SQL query
$params = Array(10, 1, 10, 11, 2, 10);
$q = "(
SELECT a FROM t1
WHERE a = ? AND B = ?
ORDER BY a LIMIT ?
) UNION (
SELECT a FROM t2
WHERE a = ? AND B = ?
ORDER BY a LIMIT ?
)";
$resutls = $db->rawQuery ($q, $params);
print_r ($results); // contains Array of returned rows
Where / Having Methods
where(),orWhere(),having() 和orHaving() 方法允許您指定查詢的位置和條件。 where() 支援的所有條件都由 having() 支援。
警告:為了使用列與列比較,只有原始條件應用作列名或函式不能作為繫結變數傳遞。
帶有變數的常量==運算子:
$db->where ('id', 1);
$db->where ('login', 'admin');
$results = $db->get ('users');
// Gives: SELECT * FROM users WHERE id=1 AND login='admin';
$db->where ('id', 1);
$db->having ('login', 'admin');
$results = $db->get ('users');
// Gives: SELECT * FROM users WHERE id=1 HAVING login='admin';
正則==運算子與列到列比較:
// WRONG
$db->where ('lastLogin', 'createdAt');
// CORRECT
$db->where ('lastLogin = createdAt');
$results = $db->get ('users');
// Gives: SELECT * FROM users WHERE lastLogin = createdAt;
$db->where ('id', 50, ">=");
// or $db->where ('id', Array ('>=' => 50));
$results = $db->get ('users');
// Gives: SELECT * FROM users WHERE id >= 50;
BETWEEN / NOT BETWEEN:
$db->where('id', Array (4, 20), 'BETWEEN');
// or $db->where ('id', Array ('BETWEEN' => Array(4, 20)));
$results = $db->get('users');
// Gives: SELECT * FROM users WHERE id BETWEEN 4 AND 20
IN / NOT IN:
$db->where('id', Array(1, 5, 27, -1, 'd'), 'IN');
// or $db->where('id', Array( 'IN' => Array(1, 5, 27, -1, 'd') ) );
$results = $db->get('users');
// Gives: SELECT * FROM users WHERE id IN (1, 5, 27, -1, 'd');
OR CASE
$db->where ('firstName', 'John');
$db->orWhere ('firstName', 'Peter');
$results = $db->get ('users');
// Gives: SELECT * FROM users WHERE firstName='John' OR firstName='peter'
NULL comparison:
$db->where ("lastName", NULL, 'IS NOT');
$results = $db->get("users");
// Gives: SELECT * FROM users where lastName IS NOT NULL
還可以使用raw條件:
$db->where ("id != companyId");
$db->where ("DATE(createdAt) = DATE(lastLogin)");
$results = $db->get("users");
或原始條件與變數:
$db->where ("(id = ? or id = ?)", Array(6,2));
$db->where ("login","mike")
$res = $db->get ("users");
// Gives: SELECT * FROM users WHERE (id = 6 or id = 2) and login='mike';
找到匹配的總行數。 簡單分頁例:
$offset = 10;
$count = 15;
$users = $db->withTotalCount()->get('users', Array ($offset, $count));
echo "Showing {$count} from {$db->totalCount}";
關鍵字查詢
To add LOW PRIORITY | DELAYED | HIGH PRIORITY | IGNORE and the rest of the mysql keywords to INSERT (), REPLACE (), GET (), UPDATE (), DELETE() method or FOR UPDATE | LOCK IN SHARE MODE into SELECT ():
$db->setQueryOption ('LOW_PRIORITY')->insert ($table, $param);
// GIVES: INSERT LOW_PRIORITY INTO table ...
$db->setQueryOption ('FOR UPDATE')->get ('users');
// GIVES: SELECT * FROM USERS FOR UPDATE;
還可以使用一系列關鍵字:
$db->setQueryOption (Array('LOW_PRIORITY', 'IGNORE'))->insert ($table,$param);
// GIVES: INSERT LOW_PRIORITY IGNORE INTO table ...
在SELECT查詢中也可以使用相同的方式關鍵字:
$db->setQueryOption ('SQL_NO_CACHE');
$db->get("users");
// GIVES: SELECT SQL_NO_CACHE * FROM USERS;
或者,您可以使用方法連結多次呼叫它,而無需通過以下方式引用物件:
$results = $db
->where('id', 1)
->where('login', 'admin')
->get('users');
刪除查詢
$db->where('id', 1);
if($db->delete('users')) echo 'successfully deleted';
排列排序方法
$db->orderBy("id","asc");
$db->orderBy("login","Desc");
$db->orderBy("RAND ()");
$results = $db->get('users');
// Gives: SELECT * FROM users ORDER BY id ASC,login DESC, RAND ();
按值排列示例:
$db->orderBy('userGroup', 'ASC', array('superuser', 'admin', 'users'));
$db->get('users');
// Gives: SELECT * FROM users ORDER BY FIELD (userGroup, 'superuser', 'admin', 'users') ASC;
如果您使用setPrefix() 功能,並且需要在orderBy() 方法中使用表名,請確保使用``轉義表名。
$db->setPrefix ("t_");
$db->orderBy ("users.id","asc");
$results = $db->get ('users');
// WRONG: That will give: SELECT * FROM t_users ORDER BY users.id ASC;
$db->setPrefix ("t_");
$db->orderBy ("`users`.id", "asc");
$results = $db->get ('users');
// CORRECT: That will give: SELECT * FROM t_users ORDER BY t_users.id ASC;
分組方法
$db->groupBy ("name");
$results = $db->get ('users');
// Gives: SELECT * FROM users GROUP BY name;
Join table products with table users with LEFT JOIN by tenantID
JOIN方法
$db->join("users u", "p.tenantID=u.tenantID", "LEFT");
$db->where("u.id", 6);
$products = $db->get ("products p", null, "u.name, p.productName");
print_r ($products);
JOIN條件
將AND條件新增到JOIN語句
$db->join("users u", "p.tenantID=u.tenantID", "LEFT");
$db->joinWhere("users u", "u.tenantID", 5);
$products = $db->get ("products p", null, "u.name, p.productName");
print_r ($products);
// Gives: SELECT u.login, p.productName FROM products p LEFT JOIN users u ON (p.tenantID=u.tenantID AND u.tenantID = 5)
將OR條件新增到JOIN語句
$db->join("users u", "p.tenantID=u.tenantID", "LEFT");
$db->joinOrWhere("users u", "u.tenantID", 5);
$products = $db->get ("products p", null, "u.name, p.productName");
print_r ($products);
// Gives: SELECT u.login, p.productName FROM products p LEFT JOIN users u ON (p.tenantID=u.tenantID OR u.tenantID = 5)
屬性共享
Its is also possible to copy properties
$db->where ("agentId", 10);
$db->where ("active", true);
$customers = $db->copy ();
$res = $customers->get ("customers", Array (10, 10));
// SELECT * FROM customers where agentId = 10 and active = 1 limit 10, 10
$cnt = $db->getValue ("customers", "count(id)");
echo "total records found: " . $cnt;
// SELECT count(id) FROM users where agentId = 10 and active = 1
子查詢
子查詢初始化
Subquery init without an alias to use in inserts/updates/where Eg. (select * from users)
$sq = $db->subQuery();
$sq->get ("users");
A subquery with an alias specified to use in JOINs . Eg. (select * from users) sq
$sq = $db->subQuery("sq");
$sq->get ("users");
子查詢 selects:
$ids = $db->subQuery ();
$ids->where ("qty", 2, ">");
$ids->get ("products", null, "userId");
$db->where ("id", $ids, 'in');
$res = $db->get ("users");
// Gives SELECT * FROM users WHERE id IN (SELECT userId FROM products WHERE qty > 2)
子查詢 inserts:
$userIdQ = $db->subQuery ();
$userIdQ->where ("id", 6);
$userIdQ->getOne ("users", "name"),
$data = Array (
"productName" => "test product",
"userId" => $userIdQ,
"lastUpdated" => $db->now()
);
$id = $db->insert ("products", $data);
// Gives INSERT INTO PRODUCTS (productName, userId, lastUpdated) values ("test product", (SELECT name FROM users WHERE id = 6), NOW());
子查詢 joins:
$usersQ = $db->subQuery ("u");
$usersQ->where ("active", 1);
$usersQ->get ("users");
$db->join($usersQ, "p.userId=u.id", "LEFT");
$products = $db->get ("products p", null, "u.login, p.productName");
print_r ($products);
// SELECT u.login, p.productName FROM products p LEFT JOIN (SELECT * FROM t_users WHERE active = 1) u on p.userId=u.id;
### EXISTS / NOT EXISTS條件
$sub = $db->subQuery();
$sub->where("company", 'testCompany');
$sub->get ("users", null, 'userId');
$db->where (null, $sub, 'exists');
$products = $db->get ("products");
// Gives SELECT * FROM products WHERE EXISTS (select userId from users where company='testCompany')
Has方法
一個方便的函式返回TRUE,如果至少存在一個滿足指定的where條件的元素,在此之前呼叫“where”方法。
$db->where("user", $user);
$db->where("password", md5($password));
if($db->has("users")) {
return "You are logged";
} else {
return "Wrong user/password";
}
Helper方法
斷開與資料庫的連線:
$db->disconnect();
重新連線,以防萬一mysql連線宕機:
if (!$db->ping())
$db->connect()
獲取最後執行的SQL查詢:請注意,函式返回SQL查詢僅用於除錯目的,因為它的執行最有可能由於char變數周圍缺少引號而失敗。
$db->get('users');
echo "Last executed query was ". $db->getLastQuery();
檢查表是否存在:
if ($db->tableExists ('users'))
echo "hooray";
mysqli_real_escape_string() 包裝:
$escaped = $db->escape ("' and 1=1");
交易助手
請記住,事務正在處理innoDB表。 回滾事務如果插入失敗:
$db->startTransaction();
...
if (!$db->insert ('myTable', $insertData)) {
//Error while saving, cancel new record
$db->rollback();
} else {
//OK
$db->commit();
}
錯誤助手
執行查詢後,您可以選擇是否有錯誤。 您可以獲取MySQL錯誤字串或上次執行查詢的錯誤程式碼。
$db->where('login', 'admin')->update('users', ['firstName' => 'Jack']);
if ($db->getLastErrno() === 0)
echo 'Update succesfull';
else
echo 'Update failed. Error: '. $db->getLastError();
查詢執行時間基準
要跟蹤查詢執行時間,應該呼叫setTrace()函式。
$db->setTrace (true);
// As a second parameter it is possible to define prefix of the path which should be striped from filename
// $db->setTrace (true, $_SERVER['SERVER_ROOT']);
$db->get("users");
$db->get("test");
print_r ($db->trace);
[0] => Array ( [0] => SELECT * FROM t_users ORDER BY `id` ASC [1] => 0.0010669231414795 [2] => MysqliDb->get() >> file "/avb/work/PHP-MySQLi-Database-Class/tests.php" line #151 ) [1] => Array ( [0] => SELECT * FROM t_test [1] => 0.00069189071655273 [2] => MysqliDb->get() >> file "/avb/work/PHP-MySQLi-Database-Class/tests.php" line #152 )
##表鎖定要鎖定表,可以使用lock方法和setLockMethod。 以下示例將鎖定表使用者以進行寫訪問。
$db->setLockMethod("WRITE")->lock("users");
呼叫另一個 ->lock() 將刪除第一個鎖。 你也可以使用
$db->unlock();
解鎖以前鎖定的表。 要鎖定多個表,可以使用陣列。 例:
$db->setLockMethod("READ")->lock(array("users", "log"));
這將鎖定表使用者,並僅記錄讀取訪問許可權。 確保你以後使用 *unlock() 或你的表將保持鎖定!
好吧!翻譯的不好,我承認使用Google翻譯出來的!外語老鳥可以直接Github看說明