Saturday, January 14, 2012

How to connect to a MySQL Database Using PHP - ABCO Technology

ABCO Technology explains, I'd like to explain to our students on creating a config file, which is the first part of creating any application.  I'll start from phpMyadmin.  Connect to the phpmyadmin interface for MySQL and create a database along with the user.  For this purpose we are going to assume that we are creating a blogtastic database for a web blog, and a user named blog_usr, with a password "password".  You will obviously have your own credentials, If the MySQL database and the PHP Code is on the same server, then your host will be "localhost", or you will have to type the name or IP address of your database server.

After the database is created, using a simple HTML editor, create a config file, in which you will create variables for your site.  These are variables that are going to be used throughout the site, and hence must be defined in the config.php file.  This also makes the website more scalable, as in the future, if you change the server or the database, you will have to only make the changes in one place.


The most important point to remember is the fact that on every page of your site, where you need to retrieve information from the database, or send information to the database, it is required to connect to the database at the very top.  


So here's a sample config.php file, that you must prepare at the start of every application.  Once the file is prepared, include this file at the top of every page using the include("config.php") or require ("config.php") function.  You may watch a video of this file at the following link: "ABCO Technology presents how to connect to MySQL from PHP"

SAMPLE CONFIG.PHP File:

<?php

//define the variables for the database

$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "password";
$dbdatabase = "blogtastic";

//Other site related variables

$config_sitename = "The Ultimate Blog";
$config_baseurl = "http://localhost/projects/blogtastic";
$config_author = "ABCO Technology";

//functions to connect to the database

$db = mysql_connect($dbhost, $dbuser, $dbpassword); //connects to the database
if(!db){
echo "Not Connected to the database";
}

$dbselect = mysql_select_db($dbdatabase,$db); //selects the database

?>

Please feel free to write comments so we can get a proper feedback.  For more information please contact us at ABCO Technology at (310) 216-3067.  This blog is part of the Advanced PHP Course taught at ABCO Technology.  Visit our website for more details.

Check Us Out We Are All Over The Web!!






Check Out Our Website

No comments: