UberPages :: Tutorials :: PHP Tutorials :: Database Connect Prep

Quick Menu

Normally when connecting to your database with PHP (or any other language), you will have to do a few things every time you're ready to connect. In the case of PHP and MySQL, you're going to specify the user name and password, the host of the database and the name of the database. Then you're going to run your code and close the connection to the database when done.

An example:

<?php
$dbhost = "localhost";
$dbuser = "USERNAME";
$dbpass = "PASSWORD";
$dbname = "DBNAME";


$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
mysql_select_db($dbname);

-----PHP CODE HERE-----

mysql_close($conn);
?>

This all seems obvious, and so does coding it out each time you're ready to interact with your database. To keep this tutorial short: It's much better to put this into includes.

As another (better) example...

I've put the first block of code into a file called db_info.php
The second block is dropped into a file called db_open.php
The last block of code is dropped into the file db_close.php

<?php
include "db_info.php";
include "db_open.php";

-----PHP CODE HERE-----

include "db_close.php";
?>

This keeps your code nice and modular, so if anything changes, all you have to change is that file, not every instance on your site. Use it!










Affiliates and Uber Linkage