問題描述
我正在努力簡化我們的數據庫助手和實用程序,我看到我們的每個函數,例如 findAllUsers(){....}
或 findCustomerById($id) {...}
有自己的連接細節,例如:
I'm working on streamlining a bit our db helpers and utilities and I see that each of our functions such as for example findAllUsers(){....}
or findCustomerById($id) {...}
have their own connection details for example :
function findAllUsers() {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
die("Connection to DB failed: " . $con->connect_error);
} else {
sql = "SELECT * FROM customers..."
.....
.....
}
}
等每個助手/功能.所以我考慮使用一個返回連接對象的函數,例如:
and so on for each helper/function. SO I thought about using a function that returns the connection object such as :
function dbConnection ($env = null) {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
return false;
} else {
return $con;
}
}
那我就可以了
function findAllUsers() {
$con = dbConnection();
if ($con === false) {
echo "db connection error";
} else {
$sql = "SELECT ....
...
}
與諸如 $con = new dbConnection()
之類的類系統相比,使用這樣的函數有什么優勢嗎?
Is there any advantages at using a function like this compared to a Class system such as $con = new dbConnection()
?
推薦答案
您應該只打開一次連接.一旦你意識到你只需要打開一次連接,你的函數 dbConnection
就變得毫無用處了.您可以在腳本開始時實例化 mysqli 類,然后將其作為參數傳遞給所有函數/類.
You should open the connection only once. Once you realize that you only need to open the connection once, your function dbConnection
becomes useless. You can instantiate the mysqli class at the start of your script and then pass it as an argument to all your functions/classes.
連接總是相同的三行:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli($srv, $usr, $pwd, $db, $port);
$con->set_charset('utf8mb4');
然后只需將其作為參數傳遞,不再使用 if
語句執行任何檢查.
Then simply pass it as an argument and do not perform any more checks with if
statements.
function findAllUsers(mysqli $con) {
$sql = "SELECT ....";
$stmt = $con->prepare($sql);
/* ... */
}
看起來您的代碼是某種意大利面條式代碼.因此,我強烈建議重寫它并在 PSR-4 中使用 OOP.
It looks like your code was some sort of spaghetti code. I would therefore strongly recommend to rewrite it and use OOP with PSR-4.
這篇關于實現mysqli連接的最佳實踐/最實用的方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!