One of the fundimentals of PHP is connecting to a MySQL server. Before you begin to use functions such as mysql_query(), you need to do 2 things.
1. Connect to the MySQL Server.
2. Select the Database.
It is very common to have your connection code in it's own file so you can just include it at the top of every page that needs to connect to the database. The reason you would want to do this is so when you need to modify the databae connection information, you only have to change it in 1 place.
// connect to the database server
if (!($db = mysql_pconnect($hostname, $mysql_login , $mysql_password))){
die("Can't connect to database server.");
}else{
// select a database
if (!(mysql_select_db("$database",$db))){
die("Can't connect to database.");
}
}
?>
You could place this code at the top of a script that you need to connect to a database, but I recommend saving this file as connect.php and put it in a directory with other files you might include. Then, when you want to use the code, just include it like in the example below.
PHP Code:
<?
include("includes/connect.php");
// now you are connected and can query the database
$request = mysql_query("select field1,field2 from table");
// loop through the results with mysql_fetch_array()
while($row = mysql_fetch_array($result)){
echo $row[0]." / ".$row[1]."<br>\n";
}
// don't forget to close the mysql connection
mysql_close();
?>