Page 1 of 1

Database connectivity....

Posted: Mon Jul 29, 2002 5:02 pm
by fatalcure
Well, currently i use this function to run my SQL queries:

Code: Select all

function query_db($query) {
$db = "db";
$dbusername = "username";
$dbpassword = "password";
	$err = "";
	$connection = mysql_connect("localhost",$dbusername,$dbpassword) or $err .= mysql_error(); 
	$database = mysql_select_db($db, $connection) or $err .= mysql_error(); 
	$result = mysql_query($query) or $err .= mysql_error(); 
	echo $err;
   mysql_close($connection); 
	return $result;
}
and everytime I have to run a query on a page i do

Code: Select all

$query = "SELECT * FROM table";
$result = query_db($query);
Now, everytime I run that script, the database connection is opened, query is run, and the connection is closed. And on some pages I run MANY MANY queries...so I was wondering, would it be better and FASTER if I used this:

Code: Select all

$db = "db";
$dbusername = "username";
$dbpassword = "password";
	$err = "";
	$connection = mysql_connect("localhost",$dbusername,$dbpassword); 
	mysql_select_db($db, $connection);
and just used:

Code: Select all

$query = "SELECT * FROM table";
$result = mysql_query($query);
instead of the query_db function, since this doesnt have to open and close the DB connection everytime....

Thanks

Posted: Mon Jul 29, 2002 6:57 pm
by fatalcure
wow, i did lil time test using microtime() to see how fast each script ran

i ran a query 1000 times and when using the query_db function (closing and reopening the db connection) it took between 1.1 to 1.35 seconds

without reopening and closing the connection, and just using mysql_query to run the query 1000 times it took between 0.30 to 0.55 seconds...

quite a difference...

Posted: Tue Jul 30, 2002 9:41 am
by RandomEngy
Yeah, I guess you answered your own question there, and others might find that useful. I have a dbconnect.php that I run every time I want to connect, and I put it at the top of every PHP document that needs to have a database connection. I havn't written my own query function yet; that could possibly make things a lot simpler for me.