实现 mysqli 连接的最佳实践/最实用的方法

Best practices / most practical ways to implement mysqli connections

我正在努力简化我们的数据库助手和实用程序,我看到我们的每个函数(例如 findAllUsers(){....}findCustomerById($id) {...} 都有自己的连接详细信息,例如:

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..."
        .....
        .....
    }

}

依此类推 helper/function。所以我考虑过使用 returns 连接对象的函数,例如:

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() 等 Class 系统相比,使用这样的函数有什么优势吗?

您应该只打开一次连接。一旦你意识到你只需要打开一次连接,你的函数 dbConnection 就变得无用了。您可以在脚本的开头实例化 mysqli class,然后将其作为参数传递给所有 functions/classes。

连接始终是相同的三行:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli($srv, $usr, $pwd, $db, $port);
$con->set_charset('utf8mb4');

然后只需将其作为参数传递,不再使用 if 语句执行任何检查。

function findAllUsers(\mysqli $con) {
    $sql = "SELECT ....";
    $stmt = $con->prepare($sql);
    /* ... */
}

看起来您的代码是某种意大利面条代码。因此,我强烈建议重写它并将 OOP 与 PSR-4 一起使用。