Please note:
This material is adapted from Build Your Own Database Driven Website Using PHP and MySQL, by Kevin Yank. 3rd Edition, published by Sitepoint Pty. Ltd. ISBN 0-9579218-1-0. The book includes much more information, and you are encouraged to buy it!
Chapter 4 Notes, page 3
Inserting Data Into the Database
Now, it would be nice to allow site visitors to insert their own great songs into the database, because only the finest people with the best taste will be visiting our site. To allow this, we can use a form:
We have used $_SERVER['PHP_SELF'] before, with the multipurpose pages. It is the action of the form, and this causes the very same page to be loaded when the form is submitted, but with three variables attached to the request. The first two, title and author, contain the title and author of the song being submitted. The third, submitsong, will always contain the value "submit." The presence of this variable is a signal that information has been submitted. All three variables, title, author and submitsong, will appear in the $_POST and $_REQUEST arrays created by PHP.
To add the information to the database, we just use mysql_query to run an INSERT query, using the $title and $author variables for the values to be submitted:
if (isset($_POST['submitsong'])) {
$title = $_POST['title'];
$sql = "INSERT INTO basicinfo SET
title='$title'
author='$author'";
if (@mysql_query($sql)) {
echo ('<p>Your song title and author have been submitted. </p>');
}
else {
echo ('<p>Error adding your song information. Probably your fault.</p>');
}
}
Putting It All Together
Now, what we have to do is jam all these little bits and pieces together into one entity that will allow a visitor to view the song titles and authors, and optionally, to add his or her own. Here is what that would look like: Ta Da!