Lesson 22

Entering Data

In this lesson you learn how to enter data into the MySQL tables you built. You learn to use both the MySQL INSERT command to add rows and to load a file of information with the LOAD DATA command.

The main way that you get—data from users on websites is through forms. In this lesson you go through the whole process from creating a form, error checking the data, adding the data to the tables, and informing the user of the success or failure of the update. You learn how to use the MySQL commands in a PHP program.

Understanding the INSERT Command

The examples in this section are based on the table1 table that you created in Lesson 19. This is the command that creates that table:

CREATE TABLE IF NOT EXISTS ‘table1’ (
  ‘id’ int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  ‘description’ text,
  ‘code’ int(11) NOT NULL DEFAULT ‘42’
) ENGINE=MyISAM

The MySQL INSERT command adds new rows to a table. You tell MySQL the table to use and then give it the values for all the fields in the new row. The following code creates a new row, assigning 1 as the value of the first field, abc as the value of the second field, and 15 as the value of the third field:

INSERT INTO ‘table1’ VALUES (‘101','abc',’15’);

The name of the table is enclosed with back ticks, which is optional for simple names. Enclose the value in quotes, regardless of whether the value is text or numeric. The quotes can be either single or double quotes. If there is a quote as part of the value, you must ...

Get PHP and MySQL® 24-Hour Trainer 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.