Monday, January 4, 2010

PHP connecting to MySQL

To open a connection to MySQL DB with PHP use the following:


$user = 'admin';
$pass = 'password';

$connection = mysql_connect($host, $user, $pass) or die ('Error connecting to mysql');

$dbname = 'tech';
mysql_select_db($dbname);
?>

Here $host is the name of MySQL server. If the webserver is on the same machine with the database server the default values can be localhost or 127.0.0.1 . $user and $pass are the valid MySQL profile name and password.

If you want for your database to work you need to select it using the mysql_select_db() function after connecting to MySQL otherwise the queries won't work.

The webhost sometimes requires the port to be specified, so if you must enter that the needed port is 8080, then you must modify the $host = 'hostname.com:8080';