PHP MySQL Connect to database tutorial will explain you How to create a connection with MySQL? with Examples.
Creating Connection to a mysql database
When you can get content out of your MySQL database, you should know how to create an connection with MySQL from inside a PHP script. To perform basic queries from within MySQL. The first thing to do is connect to the database. The function to connect to MySQL is called MySQL_connect.
Syntax for PHP MySql Connect:
$link = mysql_connect ($hostname, $username, $password, $newlink);
A call to MySQL_connect returns a link identifier on success or FALSE on failure.
- $hostname = The domain name of the mysql server. If both the web server and mysql are located on the same machine/computer, you can simply use “localhost”. Default value is “localhost:3306”.
- $username = Login ID/username of the mysql server
- $password = Password for the mysql server
Example of mysql_connect:
$username = "your_name";
$password = "your_password";
$hostname = "your_hostname";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
echo "Connected to MySQL <br />";
All going well, you should see “Connected to MySQL” when you run this script. If you can’t connect to the server, make sure your password, username and database are correct.
Closing database Connection
Closing a connection to a database is quite easy. The connection will be closed automatically when the script ends.
If you’ve used a file handle, as above, you just do this:
Code for closing the connection:
// Attempt to mysql connect to the default database server
$link = mysql_connect ("mysql_host", "mysql_user", "mysql_password") or die ("Could not connect");
print 'You are connected';