Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
    }
}

Then I could just do

function findAllUsers() {
    $con = dbConnection();
    if ($con === false) {
        echo "db connection error";
    } else {
        $sql = "SELECT ....
        ...
    }

Is there any advantages at using a function like this compared to a Class system such as $con = new dbConnection() ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
206 views
Welcome To Ask or Share your Answers For Others

1 Answer

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');

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);
    /* ... */
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...