PHP MySQL Interactive Website Design
Connecting to the MySQL Server
Before you can perform any operation on a database you must connect to the MySQL server. The syntax for performing this operation is simple.
connect_server.php
<html>
<head><title>Connect Server</title></head>
<body>
<?
$link = mysql_connect("localhost",$_POST['username'],$_POST['password']) or die(mysql_error());
print "Successfully connected.\n";
mysql_close($link);
?>
</body>
</html>
In the code shown above the red and blue syntax is all one line. The blue portion is for error trapping. (See below).
A simplified version of the code is shown below. It does not include the username, password option.
This code would be used on your PC for site development if you did not specify a username and password when you set up the MySQL server on windows.
$link = mysql_connect("localhost");
Note: Most webhosts will require you to include server name and port settings in your connect statement. The configuration shown below will work with most servers:
$link = mysql_connect(servername.com:3306,username,password);
The actual code shows how to connect using the username and password option which is required when you access the server on the internet. This configuration is used when you require your users to log in to access form processing. If log in is not required just place the actual values in the connect query statement. If used without error trapping it would be followed by a semi colon.
$link = mysql_connect("servername.com:3306",$_POST['username'],$_POST['password']);
or on some servers:
$link = mysql_connect("servername.com:3306",$username,$password);
Sample Login Form
<form method="POST" action="connect_server.php">
Enter Username: <input type="text" name="username" size="20">
Enter Password:<input type="password" name="password" size="20">
<input type="submit" value="Submit"><input type="reset">
</form>
Error Trapping
To save you from constantly visiting the error log file to find problems in your code , you can make use of a simple error reporting function provided by the mysql server. Using it with the PHP die function will help to pinpoint problem areas in your code.
The code shown below could be appended to the end of any mysql function statement.
or die(mysql_error());
Example
$link = mysql_connect("localhost",$_POST['username'],$_POST['password'])or die(mysql_error());
Closing the Connection
It is good practice to break the connection with the mysql server when operations have ceased. This simple procedure is accomplished with the line of code shown below:
mysql_close($link);
Download the Scripts
The Birthdays Database management files can be downloaded in a zip file. The package contains an integrated db management system, with a simple interface. This Instruction file is included in the download.
Download birthdays_db.zip
MySQL Tutorial
To extend your knowledge of MySQL study the Docs and Tutorials at the official MySQL website. MYSQL.com
|