.
Tutorial
Avatar

PHP basic lesson 9

By Remco on 2009-04-24
Views: 472

Introduction

This tutorial will explain to you how to connect to a database.
A connection to a database is required when you would like to interact with it ( retrieve information or send etc. )

Step 1 - Make the file

To make things easy for you we advise you to make 1 file which is going to make the database connection for you.
Call it for example:connect.php

Step 2 - Make the connection

The file is now succesfully made and we're going to put the following code into the file:



Code:


<?php

$host 
"localhost"// mysql host
$dbuser "root"// mysql username
$pass "pass"// mysql password

mysql_connect($host,$dbuser,$pass)or die('Could not connect: '.mysql_error());

?>




As you can see in the code we connect to the mysql database by using the mysql server, username and password.
This information should be provided to you by your webhost if not.. ask for the information.

to connect the function mysql_connect has been used, followed by:
"or die" which means if it fails.. do the following:
it outputs to the browser a message saying could not connect, followed by the mysql error which can help you sort out the problem if there is one.

Now run the file by browsing to it.
Example: http://www.domain.com/connect.php

if you don't get an error message it means your connection has succesfully been made.

Step 3 - Selecting a specific database on the server

Ofcourse after the connection has been made.. you need to specify with what database you want to work.
This will be the database provided to you by some one or a self made database.

For example:
My database name could be: website
which contains all my information


if i want to select this database my code would be:



Code:


<?php

$host 
"localhost"// mysql host
$dbuser "root"// mysql username
$pass "pass"// mysql password
$dbname "website"// the required database name

mysql_connect($host,$dbuser,$pass)or die('Could not connect: '.mysql_error());
mysql_select_db($dbname) or die(mysql_error());

?>




Congratulations you now have a correct working connection with your database.
In the next tutorial i will teach you how to create a database by using PHP.
« Previous Next »




Comments

You have to be logged in to write a comment.

.