Connect to a MySQL Database using PHP
by Varun ThirayanAPDZ.com
Friday, 17th March 2006
Step 1
Find your favourite text editor, even Notepad will work. Open it up and create a new document.Step 2
In Notepad copy and paste this code, we will break it down after.<?php
/* DB CONNECTION INFO */
$username="mysql_username";
$password="password";
$host="localhost";
$database = "mysql_database";
/* ESTABLISH THE CONNECTION */
mysql_connect($host,$username,$password) or die("Error connecting to Database!
" . mysql_error());
mysql_select_db($database) or die("Cannot select database!
" . mysql_error());
?>
/* DB CONNECTION INFO */
$username="mysql_username";
$password="password";
$host="localhost";
$database = "mysql_database";
/* ESTABLISH THE CONNECTION */
mysql_connect($host,$username,$password) or die("Error connecting to Database!
" . mysql_error());
mysql_select_db($database) or die("Cannot select database!
" . mysql_error());
?>
Ok, as you can see, the sections are labeled. The section we will be dealing with is the first one called /* DB CONNECTION INFO */. Underneath you will notive 4 PHP variables being set-up, these are $username, $password, $host and $database. Your webhost should have given you your MySQL connection info when you registered, if not.... please stop reading this tutorial.
Get your MySQL user name, and where you see "mysql_username" in your text editor delete everything between the quotes and replace it with YOUR MySQL username.
Get your MySQL password, and whare you see "password" in your text editor delete everything between the quotes and replace it with YOUR MySQL password.
The $host part will usually never change from "localhost", so don't worry about it.
The database is dependant on which one you want, you probably know how to make a database in MySQL by clicking "Creat New Database" in PHPMyAdmin. So let's pretend your database name is "test".
Get your MySQL database name (in this case "test"), and where you see "mysql_database" in your text editor delete everything between the quotes and replace it with YOUR MySQL database ("test").
Almost done! - Now save your file as config.php or something similar. Next upload it to your webserver and in a browser go to www.yourdomainname.com/config.php. If everything is OK then the page will be completely blank! Yay!! If not then you will see a bunch of MySQL jargen that will make absolutely no sense at all, in this case please re-read the tutorial.
Now that you are connected to your database you can include this file with the php include function (tutorial coming soon) and you can use MySQL anywhare on your website (As long as it is all PHP).
Options:
Printer Friendly
Email Friend
