Search code examples
phpperformancefunctionglobal-variablesdatabase-connection

Improve PHP performance : PHP $_SESSION v mysqli($servername, $username, $password, $dbname)


I want to improve performance in my PHP code.

I have a login script which creates a session and assigns username and password

$_SESSION['name'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];

I have my main script with many functions which query the db with

$servername = "localhost";  $username = $_SESSION['name'];  
$password = $_SESSION['password'];  $dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

Is there better way than creating a new connection in every function?

new mysqli($servername, $username, $password, $dbname)

Do new mysqli connections slow the performance uneccessarily when I have a session?

Could I for example declare a global $conn and reuse it in every function?


Solution

  • in php, globals can be a bit of a debate, check out this post for example: Are global variables in PHP considered bad practice? If so, why? .

    Personally I am in the globals are bad camp. You shouldn't need to create a new connection for every function. Ideally (in my opinion at least) you should create a single connection object and then pass that around your program (i.e. dependency injection https://codeinphp.github.io/post/dependency-injection-in-php/).

    If you're not currently using OOP then this would be as simple as defining it as a parameter e.g.

    functionName(String $var1, int $var2, mysqli $conn) {
       //do your stuff
      
    }
    

    Do new mysqli connections slow the performance unnecessarily when I have a session?

    It depends. The session should be used for persisting data across scripts, so you should be wary of what you store in there but yes you can use it to save you making requests on every page. Then you can just use isset($_SESSION['your-session-name']) to check whether or not you need to do the call

    I would strongly advise against doing this:

    $_SESSION['name'] = $_POST['username'];
    $_SESSION['password'] = $_POST['password'];
    

    firstly, you're not sanitising your data at all - remember you can never trust data from anywhere. Secondly passwords shouldn't be stored in the session and shouldn't be saved in plain text anywhere, and thirdly the log in details to your site shouldn't be the same as the credentials to your database. Database credentials should come from an independent source such as a .env of .ini file - this should also not be saved in your version control