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.
| 1 | <? |
| 2 | include "connect.php"; |
| 3 | ?> |
or if you wish to limit the connection to only one time
| 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.
| 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:
| 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:
| 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
| 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.
| 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:
Source: http://simplythebest.net/scripts/snippets/connect_to_MySQL_database.html
Post a Comment