PHP mysqli db Connect

Johnatan56

Honorary Master
Joined
Aug 23, 2013
Messages
30,955
Hi,

I have a question in regards to best practice.

Currently I have a php file called dbConnStart which starts the database connection:
Code:
    $serverName = "localhost";
    $username = "root";
    $password = "";

    //create connection
    $conn = new mysqli($serverName, $username, $password);

    //check connection
    if($conn->connect_error) {
        die("connection failed: " . $conn->connect_error);
    }

And then when I need a database connection in the file I do something like:
Code:
    //start database connection
    include('../dbConnStart.php');

    //create database
    $sql = "CREATE DATABASE shoppingCart";
    if($conn->query($sql) === TRUE){
        echo "Database created successfully";
    } else {
        echo "Error creating database: " . $conn->error;
    }

    //close database connection
    $conn->close();


Is there a better way? Currently each connection has to be opened and closed as required, what if I had maybe three or four connection I had to use in quick succession?
I'd probably go along the lines of:
Code:
//do file 1,2,3

//start db connection
include('../dbConnStart.php');

//include the php files that require the connection
include('file1.php');
include('file2.php');
inlcude('file3.php');

//close db connection
$conn->close();

Kind Regards,
J
 

stricken

Expert Member
Joined
Sep 5, 2010
Messages
2,265
Yes. Never open a connection for each query / web transaction. Open a connection and re-use it until done. You can get into connection pools later on for even more performance.
 
Top