Page is a not externally linkable
- Code, Content, and Presentation
-- PHP Server Side Scripting
---- Perfect Database Connection


bateman_ap - 2:07 pm on Jul 28, 2009 (gmt 0)


I have started on PHP from classic ASP, the leap to .net was jsut too much for my non-programming brain to handle.

I have made a few sites and it's all going well, however I remember when I learnt ASP I began by using a terrible connection method to the database and only realised a couple of years later, changing it to a better method speeded up my pages no end.

So I wonder if you could look what I am doing at the moment in PHP and tell me if it's OK or could be made better?

I currently use a include file, ie connect.php, that contains my database connection and connection string:


<?
/*--------- DATABASE CONNECTION INFO---------*/
$hostname="localhost";
$mysql_login="username";
$mysql_password="password";
$database="db_test";
// connect to the database server
if (!($db = mysql_connect($hostname, $mysql_login , $mysql_password))){
die("Can't connect to database server.");
}else{
// select a database
if (!(mysql_select_db("$database",$db))){
die("Can't connect to database.");
}
}
?>

I then in my code would do something like this:


$sql = "SELECT tbl_test.fld_test FROM tbl_test";
$result= mysql_query($sql) or die(mysql_error());
while ($sqlrow= mysql_fetch_assoc($result)) {
...do my thing
}

One prob obvious thing is that I still use the above loop even when I know I'm only getting back one result.

Many thanks for any help


Thread source:: http://www.webmasterworld.com/php/3961035.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com