CREATE TABLE task (
taskid INT AUTO_INCREMENT PRIMARY KEY,
userid INT,
thedate DATE,
description TEXT
);
The taskid field will act as your uniquely identifying ID number for each task (and will let the auto_increment and primary key features handle its integrity). The userid field will be used as a foreign key to associate the task with the user who set it up. The thedate field will store a date value (YYYY-MM-DD) for each task, and the description field will house the actual task description itself. For the purposes of this example, you will populate the table with these fields:
INSERT INTO task (userid, thedate, description) VALUES
(1,'2005-12-04','Finish chapter 4');
INSERT INTO task (userid, thedate, description) VALUES
(1,'2005-12-25','Christmas!');
Next, you will set up the user table that will allow you to store users that can enter tasks into the system.
CREATE TABLE user (
userid INT AUTO_INCREMENT PRIMARY KEY,
name TINYTEXT
);
This table will house a unique identification number (userid, to associate with the task table) and a name field to house the name of the user. You will add one record to this table:
INSERT INTO user (userid, name) VALUES ('1','Lee Babin');
Once the tables are created, it is time to set up a database connection script. In order to connect to a database using the PHP MySQL library, you must supply the connection information to the mysql_connect function. Consider the following block of code, which will allow you to connect to your MySQL database:
//dbconnector.php
//Define the mysql connection variables.
define ("MYSQLHOST", "localhost");
define ("MYSQLUSER", "apressauth");
define ("MYSQLPASS", "tasks");
define ("MYSQLDB", "taskdb");
function opendatabase(){
$db = mysql_connect (MYSQLHOST,MYSQLUSER,MYSQLPASS);
try {
if (!$db){
$exceptionstring = "Error connecting to database:
";
$exceptionstring .= mysql_errno() . ": " . mysql_error();
throw new exception ($exceptionstring);
} else {
mysql_select_db (MYSQLDB,$db);
}
return $db;
} catch (exception $e) {
echo $e->getmessage();
die();
}
}
?>
As you can see here, the dbconnector.php script, which creates a connection to the database, is both simple and efficient. By including this in whatever file you deem necessary, you can perform database queries by merely referencing the $db variable. By keeping the database login information in one place, you cut down on any maintenance you may have to perform should you decide to change the database connection information. You also limit the security risks by not spreading around database information.
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
0 comments:
Post a Comment