314
Insert New Data into a Table with PHP (continued)
Create the PHP Script
1 In your editor, open a new
PHP page.
2 Delete any existing code your
editor might add so that the
page is completely blank.
3 Type <?php.
4 Type include(“?”);,
replacing? with the path to
your database connection
script.
5 Type $formfield1 = $_
POST[‘formfield1’];,
replacing formfield1 with the
name of the first field from
the form.
6 Repeat Step 5 to create
shorter variable names for
the remaining form fields.
7 Type $query = “INSERT
INTO table (field1,
field2) VALUES
(‘$formfield1’,
‘$formfield2’)”;,
replacing table with the name
of the table, field1 and field2
with the names of the
database fields, and $formfield1,
$formfield2 with the variables
created in Steps 5 and 6.
Insert New Data into a Table with PHP (continued)
O
nce you have created your form, you must create the PHP page to process the form. In this case,
the page must contain a SQL INSERT INTO statement to add the record to the database. The
INSERT INTO statement takes the name of the table, followed by a list of the fields into which
you will be adding data. You then use the VALUES keyword followed by a list of the form fields that
contain the new data. Once complete, you can use the PHP header() function to redirect your
user to a page that displays the records in the table.
1
4
6
8
9
3
5
7
8 Type $data =
mysql_query($query);.
9 Type header(“location:
?”);, replacing? with the
path to a page that displays
the table’s data.
Note: See the section “Display the
Contents of a Table on a Web Page”
earlier in this chapter for details on
creating this page.