Forum Moderators: coopster
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
$db = mysql_connect($hostname, $mysql_login , $mysql_password) or die("Can't connect to database server.");
// select a database
mysql_select_db("$database",$db) or die("Can't connect to database.");
it does the same thing, I doubt you would ever notice a speed difference abd the other model might be useful if the error handling was more complex.
I also must mention, though I am sure you know, to store your db login credentials in a separate file and outside of the web root if at all possible
your query extraction code looks standard, if you know you are getting a single result you could use mysql_result or an if statement or num_rows to be sure, then whichever you like
I also must mention that we don't leave 'or die' code in live/production scripts, you need to handle the errors nicely
On a different note, I'm surprised you did classic asp but couldn't handle the move to .net. Coming from someone who has done both, php is a lot more coding intensive than .net. Asp.net has all of the fancy gui based interfaces to code with. I personally like PHP better, but that is because I fell more in control because of the coding requirements.
I think the GUI interfaces are the ones I can't get to grips with, I think if someone just showed me how to do a select, loop through some results and format them how I want to in .net I would have been OK, it kept wanting to put them in stupid datagrids and suchlike, I just found php to be closer to what I was used to.