Search  
   
Browse by Category
 
Netfirms 24/7 Support .: DATABASE MANAGEMENT .: How do I connect to a mySQL database using PHP?

How do I connect to a mySQL database using PHP?

To connect to a database via PHP, you must be familiar with PHP scripting as well as MySQL commands.

Below is a sample program using PHP to interact with a MySQL database, which has been commented to explain each function (where username is the database username, password is the database password and and dbid is the database id for the database you wish to connect to):

<?
$hostname = "mysqlhost";
$username= "username";
$password= "password";
$dbid="dbid";
$link=mysql_connect($hostname, $username, $password);
mysql_select_db($dbid) or die ("Unable to connect to MySQL");
print "Connected to MySQL
";
mysql_close($link);
?>

NOTE: The mysql password should be no more than 8 alpha-numeric characters. To identify the database username, password and dbid, click here for further instructions.

For remote connections:

<?
$hostname = "mysqlhost.netfirms.com:3306";
$username= "username";
$password= "password";
$dbid="dbid";
$link=mysql_connect($hostname, $username, $password);
mysql_select_db($dbid) or die ("Unable to connect to MySQL");
print "Connected to MySQL
";
mysql_close($link);
?>

For remote connections where the database is residing on a different/separate Netfirms hosting account:

A. Identify the NF_MYSQL_HOST address for the account where the database resides:

1. Login to the Netfirms Members Control Panel at https://controlpanel.netfirms.com
2. Click Site Tools
3. Click Environment
4. Refer to the NF_MYSQL_HOST line entry and jot down the value indicate (eg. It will look similar to: NF_MYSQL_HOST=10.8.12.2:3306 but the IP address may be different for your acocunt)

B. Code your PHP script on the account that needs to make the remote database connection

1. The first line of your PHP script that will make a remote connection to your database residing on Netfirms should look similar to:

putenv("NF_MYSQL_HOST=10.8.12.2:3306");

Below is a sample code:

<?
putenv("NF_MYSQL_HOST=10.8.12.2:3306");
$hostname = "mysqlhost.netfirms.com:3306";
$username= "dbUsername";
$password= "dbPassword";
$dbid="dbid";
$link=mysql_connect($hostname, $username, $password);
mysql_select_db($dbid) or die ("Unable to connect to MySQL");
print "Connected to MySQL";
mysql_close($link);
?>

How helpful was this article to you?


.: Powered by Lore 1.5.6
Visit Netfirms.com Web Hosting | Copyright © 1998 - 2006 Netfirms, Inc. All Rights Reserved.