Connect to a MySQL database

To connect to a MySQL database to make the data from the database available in your Web application, you can do two things:
1. create a connect.php page, and ‘include’ this page in the PHP page(s) where you need the connection to the database.

 PHP |  copy code |? 
1
<?
2
include "connect.php";
3
?>
or if you wish to limit the connection to only one time
 PHP |  copy code |? 
1
<?
2
include_once ('connect.php');
3
?>
2. insert the code in the PHP page 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.

 PHP |  copy code |? 
1
<?
2
@mysql_connect ("localhost"," username","password") or die ("Cannot connect to database");
3
@mysql_select_db ("name_of_database ") or die ("Cannot find database");
4
?>
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:

 MySQL |  copy code |? 
1
$db=@mysql_connect("localhost","username","password") or die("Could not connect to database");
2
@mysql_select_db("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:
 ABAP |  copy code |? 
1
define ('MYSQL_HOST', 'localhost');
2
define ('MYSQL_USER', 'username');
3
define ('MYSQL_PASS', 'password');
4
define ('MYSQL_DB', 'name_of_database');
5
 
6
$dbhost = MYSQL_HOST;
7
$dbusername = MYSQL_USER;
8
$dbpassword = MYSQL_PASS;
9
$dbname = MYSQL_DB;
or simply
 MySQL |  copy code |? 
1
$dbhost = 'localhost';
2
$dbusername = 'username';
3
$dbpassword = 'password';
4
$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.
 MySQL |  copy code |? 
1
$connection = @mysql_connect("$dbhost","$dbusername","$dbpassword") or $DB_ERROR = "Could not connect to server.";
2
$db = @mysql_select_db("$dbname", $connection) or $DB_ERROR = "Could not select database.";
3
 
4
if ($DB_ERROR==''){
5
//whatever you wish to do here.
6
}
When you’re done with the database, you can close the connection with:
 MySQL |  copy code |? 
1
mysql_close($db);

Source: http://simplythebest.net/scripts/snippets/connect_to_MySQL_database.html

  • Share/Bookmark
No Responses to “Connect to a MySQL database”

Post a Comment