PHP/MySQL Tutorial – PHP MySQL Connection

By | March 13, 2013

PHP/ My SQL Tutorial – PHP/ My SQL connection

Method of connecting to your database

Step 2: Set up a connection with the My SQL database. Because improper connection will lead to failure of queries to the database, if the script is not connected to its database.

It will be good if you can select the username, password and the database name at the beginning of the script code. So it can be easily changed, if you want to change them in future.

$username= “your_username”
$password= “your_password”
$database= “your_database”

Replace “your_username”, “your_password” and “your_database” with the My SQL username, password and database which will be used by your script.

Here, if you are worried about the security factor of keeping the password in the file, then don’t worry! Because PHP source code is processed by the server before sending to the browser. As a result visitors will not be able to notice the script’s code in the page source. We provide Entreprise Web Hosting India

Inway Hosting next step, PHP script has to be connected to the database through mysql_connect PHP function:

mysql_connect (local host, $username, $password);

Above line signifies that, PHP should connect to the My SQL database server at “Local Host”, which is the My SQL server and runs on the same server mentioned in your script.

Select the database, you want to use, after establishing a successful connection. Database can be accessed by your username and can be completed with the help of following command:

@mysql_select_db ($database) or die (“Unable to select database”);

This line signifies PHP to get connected to the My SQL database server at “Local Host” (which is the My SQL server and runs on the same server as mentioned in your script.)

Select the database, you want to use after establishing a successful connection. The database should be accessed by your username, and this can be accomplished with the help of following command:

@mysql_select_db($database) or die( “Unable to select database”);

This indicates PHP to choose the database stored in variable $Database (for .e.g. the selected database will be “ your_database”). If there is any problem with the script while making connection, it will stop executing and you will receive an error message.

Not Able to select a Database

The debugging function is performed by “or die” part, but it is not necessary.

Another very important function of PHP is

mysql_close ();

It closes the connection of the database server. Even if you do not include this function your script will run. And if you have opened too many My SQL connections it can cause problem to your account. So, it is good to close the connections, once all queries are operated.

Now you got connected to the server and opted the database with whom you want to work, so, start querying the database. We provide best web hosting india

Leave a Reply