Loading a Database Record into a Form

Problem

You want to display a form but initialize it using the contents of a database record. This allows you to present a record-editing form.

Solution

Generate the form as you usually would, but instead of using the usual defaults, set the form elements to the values of columns in the database record.

Discussion

The form field generation examples shown in earlier sections have either supplied no default value or have used the default value as specified in an ENUM or SET column definition as the field default. That’s most appropriate for presenting a “blank” form that you expect the user to fill in. However, for applications that present a web-based interface for record editing, it’s more likely that you’d want to fill in the form using the content of an existing record for the initial values. This section discusses how to do that.

The examples shown here illustrate how to generate an editing form for records from the cow_order table. Normally, you would allow the user to specify which record to edit. For simplicity, assume the use of the record that has an id value of 1, with the following contents:

mysql> SELECT * FROM cow_order WHERE id = 1\G
*************************** 1. row ***************************
         id: 1
      color: Black & White
       size: large
accessories: cow bell,nose ring
  cust_name: Farmer Brown
cust_street: 123 Elm St.
  cust_city: Katy
 cust_state: TX

To generate a form with contents that correspond to a database record, use the column values ...

Get MySQL Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.