Creating MySql connection – php

Quite elementary but very useful piece of information for new web developers. Connecting to Mysql from php is quite easy because of number of functions provided by php.

It uses mysql_connect function to connect to MySql, which returns connection object handle and that can be used for rest of the read/write operations with MySql DB. This function take some parameters which are listed below and also shown in example below:

1. $hostname : The machine name where MySql server is running. Generally it runs on the same machine as of webserver and you can specify ‘localhost’ or ’127.0.0.1′ for this parameter but in case MySql database is running on separate machine. You need to specify its machine name or IP address.

If it is not running on standard port you also need to specify the port like below:

 
$hostname='122.45.23.111:3305'; // specify host:port (standard port is 3306)  
 


2. $user : dbuser required for authentication and authorizations.
3. $password : dbuser password for authentication.
4. $database : This is required to set the context before executing read/write SQL queries. mysql_select_db function is used to select the database using this parameter.

 
<?php
$hostname='localhost'; // specify host  
$user='root'; // database user name  
$password='root'; // database password  
$database='test'; // database name  
$connection = mysql_connect("$hostname" , "$user" , "$passwprd")  or die ("Unable connect to MySQL");
$db = mysql_select_db($database , $connection) or die ("Can't find database.");
?>
 



It is recommended that you should keep the connection information and its creation in separate php file and it should not be part of php files with other code for logic and display.

Use include directive for including php files with connection params and connection creation. See example below:

 
include 'config.php';
include 'dbconnection.php';
 


Most Commented Posts

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)