[back]

Populating the Database

There are several ways that you can add information to your "students" table. We will look at three methods. First, you could create a PHP page that will insert info into each field. The second method is to create an HTML form that passes information to the PHP page. Later, we will see how to insert an already existing excel or other database file into a MySql database.

Method 1: Using a PHP script

<?
$user="mills";
$password="123";
$database="class";

mysql_connect(localhost,$user,$password);
@mysql_select_db($database) or die( "Unable to select database");

$query = "INSERT INTO students VALUES ('','John','Smith','2005','012345')";

mysql_query($query);
mysql_close();

echo "data inserted";

?>

Method 1 explained:

We would now like to create a record for John Smith in our 'students' table.

first name: John
last name: Smith
grad year: 2005
student number: 012345

to input this information, simply change the $query variable to:
$query = "INSERT INTO students VALUES ('','John','Smith','2005','012345')";

The new $query tells the PHP to INSERT INTO the table called 'students' the VALUES in the brackets which follow.

Each set of quotes ' ' , should contain one piece of information. It uses all the fields in order and inserts the information from between the quotes.

For example:
'John' will be inserted into the 2nd field which, in this table, has been named the 'first' field.

Notice, however, that you are not inserting any value into the first field in the database (id). This is because this field is going to act as an index field. No two records in the database will have the same ID because we set this field to 'Auto Increment'. This means that if you assign it no value it will take the next number in the series. The first record will have the value of 1.

Note: Since we set each field to be "Not Null", each field must contain a value.

Create a new page called insert1.php and add John Smith to the table.