Open the DB connection for each PHP page load?

Is the following snip of PHP code something that should be run once for a given session? Or should it be executed every time a PHP page on my site is loaded by the user? Right now its executing with every page load and I’m thinking that this may not be efficient.

$databaseConnection = @mysql_connect (localhost, username, password);

Thank you.

You just need the one database connection, which can be used by all the code that needs it. Non-persistant database connections are automatically closed once a script has finished executing.

It’s bad practice to use the @ operator to suppress errors, all errors should be handled (the modern method is exceptions (try-catch blocks).

You need to be aware that the old mysql_* extension is deprecated, you need to migrate over to either the mysqli_* extension or PDO. Both of them have the ability to use prepared statements (which prevent SQL injection attacks), PDO has the advantage of allowing named parameters.

In any case you need to make sure that any user submitted data is validated, checking things like is it of the type you expect, is it of the size that you expect, etc.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.