Home > MySql > MySQL PHP Connection

MySQL PHP Connection

Before you can do anything with MySQL in PHP you must first establish a connection to your web host’s MySQL database. This is done with the MySQL connect function.

Syantax

mysql_connect(servername,username,password);

Example

mysql_connect(“localhost”,”guest”,”abc123″);

Example with PHP

In the following example we store the connection in a variable ($connection) for later use in the script. The “die” part will be executed if the connection fails:

<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = ‘localhost’;
$dbuser = ‘guest’;
$dbpass = ‘abc123′;
$connection = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $connection)
{
die(‘Could not connect: ‘ . mysql_error());
}
echo ‘Connected successfully’;
mysql_close($connection);
?>
</body>
</html>

You can disconnect from MySQL database anytime using another PHP function mysql_close().

Categories: MySql Tags:
  1. No comments yet.
  1. No trackbacks yet.