Connecting to a MySQL Database

What you Need:

  • Notepad
  • MySql Database
  • Server with APACHE and MySQL set up (for testing i use XAMPP)

How To
Connecting your code to a MySQL database can open up all sorts of possibilities, without it the comments section here would not be available, and i wouldn’t be able to update this website through my Admin panel. It is vital part of current and future web design and is only becoming more popular with the advent of Web 2.0. So how do you connect to a MySQL database? well all you need is the code below.

<?php
//Database Variables
$databaseHost = "localhost";
$dbusernane = "username";
$dbpassword = "password";
$dbName = "yourDatabase";

//connect to the database
$connect = mysql_connect($databaseHost, $dbUsername, $dbPassword) or die('Could not connect to MySQL: '. mysql_error());

//select Database
$conn = mysql_select_db($dbName, $connect)or die('Could not select the Database: '. mysql_error()) ;
?>

Lets look at these variables a little more closely.

$databaseHost: This should be set to the I.P address or server name that you have your database set up on, some ISPs or web hosting services will provide you with an I.P address, however for the most part you should set this value to “localhost” or 127.0.0.1.

$dbUsername: This should be set to the username which contains privileges to make changes to your database, again this might be provided for you, However if you set up a database yourself you should set the username to the one you created.

$dbPassword: This should be the password that correlates with your username.

$dbName: Set this to the name of the database you will be editing.

or die(): Tells php to display your custom error message if the query fails.

mysql_error(): retrieve and display the error from SQL.

That’s all there is to it folks, later i will be going into storing and retrieving data from a database.

  1. No comments yet.

  1. No trackbacks yet.

You must be logged in to post a comment.

Secured for spam by MLW and Associates, LLP's Super CAPTCHASecured by Super-CAPTCHA © 2009-2010 MLW & Associates, LLP. All rights reserved.