Database basics: Connect to a Mysql Database

This tutorial is part of the Tutorial Series Database basics !, Let us learn and try to understand how connecting a mysql database works in PHP

Before learning how to connect to a database we should know how to create a database , For creating a database there are several methods that we can use , Some of the most common methods are Phpmyadmin , Cpanel Mysql database panel and Command line.

Let’s learn the method of connecting to the database, For this create a file called db_operations.php and put these contents there




[php]
$host = "localhost";
$username = "root";
$password = "";
$conn = mysql_connect ($host, $username, $password);
mysql_select_db("cooking");
[/php]

Here the variables $host , $username and $password are the three variables that we use to connect to the database , The $host contains the database server name , usually it’s a localhost or a ip address !

$username and the password are the mysql username and password that you require to connect to a database.

Once we have these three login credentials we can easily connect to the database , The mysql function mysql_connect is used to connect to a database . For example

$conn = mysql_connect ($host, $username, $password);

Here mysql_connect is connecting to the server and storing the output value in the variable $conn, The variable $conn contains the connection handle and can be used anywhere to refer this particular connection.

We have also used the die() function with the mysql_connect which will make the script exit when a successful connection is not made !, Any error occured at unsuccessful connection will print on the browser due to the function mysql_error() called in the die function .

After connection we can easily connect to any database we want and work on sql operations.

Let us know what you think of this particular post ! , Any suggestions , comments are welcome !

2 thoughts on “Database basics: Connect to a Mysql Database”

Leave a Reply