Example 8: Connecting a form to a database

php makes it easy to connect a form to a database. First a HTML form is used for input. These values are passed to a php page. (See example 7) The php processes the form values into an SQL query. The query is passed to the database. (See example 5) For this example I will use the tables from example 6.

The simplest way to do this is similar to phpMyAdmin's SQL page. You can simply create a page with a textarea and a submit button. The user would be required to type the SQL query, and php would foreword the query to the database. This is not user-friendly in most applications. People other than the database administrator should not have this kind of access. A better solution would be to create an insert form or a query form. For this example, I will show an insert form. Other queries will be very similar. Note that this insert form is not secure.

See the code in example-8a.php and example-8b.php.

The first page is a php generated HTML form. The form is very simple except for the genre field. This field is created using a query to the table of genres. Submitting this page sends the form data to the second php page. This page displays the values, then issues a SQL insert query to the database. This example has no error checking. For an actual system it is important to use error checking.

© 1996 -- 2009, Noel Schutt
Page last updated: 2009.04.29