CONNECTING TO A MYSQL DATABASE

 

None of our tutorials have dealth with a database yet, and that is for the sole reason that not everyone has access to a database, however for those who do this tutorial will teach you how you can connect to your database. We wont be covering SQL queries and the conversion of SQL queries into PHP in this tutorial, you can look for a tutorial on that later on. First i suggest we get the hang of this.

Lets start by defining some variables. We will need to define the $dbuser, $dbpass, $dbhost and $db variables. These will hold the username and password for access to the database, the database host (99% of the time its localhost) and the database name. Here is how we accomplish this:
<?php
$dbuser = "mysql_username";
$dbpass = "mysql_password";
$dbhost = "localhost";
$db = "db_name";
?>
Now we just fill the username, password, host (if needed), and database name with out own information.

Now we can use those variables to connect to the MySQL server. To do this we need to follow the mysql_connect format of host, username, password.
<?php
mysql_connect($dbhost, $dbuser, $dbpass);
?>

Now we need to select the database we wish to work with. We do this with the mysql_select_db function.
<?php
mysql_select_db($db);
?>

Now if you know any SQL queries now is a perfect time to run them. When you are finished you can close the connect with the mysql_close(); function. Here is the complete code:
<?php
$dbuser = "mysql_username";
$dbpass = "mysql_password";
$dbhost = "localhost";
$db = "db_name";

mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($db);

// Query etc goes here

mysql_close();
?>

Hosted by www.Geocities.ws

1