Database connectivity....

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
fatalcure
Forum Contributor
Posts: 141
Joined: Thu Jul 04, 2002 12:57 pm
Contact:

Database connectivity....

Post 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
fatalcure
Forum Contributor
Posts: 141
Joined: Thu Jul 04, 2002 12:57 pm
Contact:

Post 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...
User avatar
RandomEngy
Forum Contributor
Posts: 173
Joined: Wed Jun 26, 2002 3:24 pm
Contact:

Post 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.
Post Reply