mysql - Efficient way to connect to a database when multiple functions are running queries -


i'm writing application has functions.php file javascript file accessing via ajax. have each function connecting database, running queries, closing database. know there has more efficient way of doing this. i'd input database credentials once , have functions use it. whats efficient way this? i've read quite few of answers here on topic they're different , i'm lost. point me in right direction :)

currently functions opening database this.

$db = new mysqli("hostname", "username", "password"); $db -> select_db("database name"); 

or this

mysql_connect("hostname", "username", "password"); mysql_select_db('database name') or die( "unable select database"); 

you can check whether database connection variable set:

if (!isset($db)) {     $db = new mysqli(...);     $db->select_db("database_name"); } 

and mysql_connect (it returns connection resource, can assign variable, though it's optional argument other functions).

another way use function static variable:

function connect_db() {     static $db = new mysqli(...);     static $selected = $db->select_db("database_name");     return $db; } 

a third options connect database once @ beginning of script, instead of in each function. either pass $db each function, or access global $db;.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -