最佳实践/最实用的方法来实现mysqli连接 [英] Best practices / most practical ways to implement mysqli connections

查看:73
本文介绍了最佳实践/最实用的方法来实现mysqli连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力简化数据库帮助程序和实用程序,并且看到我们的每个函数(例如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()之类的Class系统相比,使用这样的函数是否有任何优势?

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.

连接始终是相同的三行:

The connection is always the same three lines:

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连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆