MorkaLork Development

Interesting stuff I've picked up over the years...

PHP/MySql part 2: Connection

2009-04-17 07:32:52 | 178 views | sql mysql php connection database

A connection can be done in differant ways in PHP.

I normally use the following modell:


function ConnectDB()
{
$host="localhost"; // Host name
$username="MyUsername"; // Mysql username
$password="MyPassword"; // Mysql password
$db_name="MyDB"; // Database name
$tbl_name="MyTable"; // Table name

mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

}

This holds the connection open, but you can also save the connection in a variable and use it with the queries, like this:



$link = mysql_connect("localhost", "MyUsername", "MyPassword");

if(mysql_query("DO SOMETHING", $link))
{
echo "Something has been done!";
}
else
{
echo "Something was not done =(";
}


It depends on what you want to do. Both these ways work, just don't forget, when you're done:


mysql_close();


It's good mannors to close the connection =D








Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.