Connect to MySQL Database

More tags

Connect to MySQL Database
PHP snippet to connect to a MySQL database using a file for the connection and an include statement in the page needing to connect.
Author: SimplytheBest Inc Price: Free GPLv2 Type: PHP,MySQL

Connecting to a MySQL database to make the data from the database available in your Web application, can be done in many different ways. Here are two often used methods.

1. create a connect.php page, and 'include' this page in the PHP page(s) where you need the connection to the database.

include "

or if you wish to limit the connection to only one time

include_once ('

2. insert the code in the PHP page where and when needed.

In both cases, insert the code below to make the connection. Either you place it in the connect.php if you use that option or in the PHP page where you need to connect.

@mysql_connect ("
localhost"," username","password") or die ("Cannot connect to database");
@mysql_select_db ("name_of_database ") or die ("
Cannot find database");

You can also use die ('Could not connect: ' . mysql_error()); if you do not want to define the error message.

A little more elaborate would be:

$db=@mysql_connect("localhost","username","password") or die("Could not connect to database");
name_of_database") or die("Could not find data");

Even more sophisticated would be to create a connect.php or config.php page and insert the following statements:

define ('MYSQL_HOST', 'localhost');
define ('MYSQL_USER', '
define ('MYSQL_PASS', '
define ('MYSQL_DB', '

$dbhost = MYSQL_HOST;
dbusername = MYSQL_USER;
dbpassword = MYSQL_PASS;
dbname = MYSQL_DB;

or simply

$dbhost = 'localhost';
dbusername = 'username';
dbpassword = 'password';
dbname = 'name_of_database';

The benefit of the define() function is that you can easily set the variable values using an edit config page, or call f.e. MYSQL_HOST to get the variable value as is set in the config.

Resuming it all and using MySQLi, place the connection in connect.php:

$con = @mysqli_connect("$dbhost","$dbusername","$dbpassword","$dbname");
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQLi: " . mysqli_connect_error();

All calls to a mysqli-query will then be thus:

$sql0 = "SELECT * FROM YourTable WHERE your_id = ".$_REQUEST['id'];
$rs_query = mysqli_query($con, $sql0);
$resultrow = mysqli_num_rows($rs_query);

When you're done with the database, you can close the connection with:



Hope this makes you happy enough to link to us! =:)