Lesson 23

Selecting Data

In this lesson you learn how to retrieve data from the database. The SELECT command is arguably the most common MySQL command you use in PHP programs. It is also one of the most complex, with clauses that enable you to choose what table(s) you use, which columns are returned, what conditions must be met before a row is selected, what order to sort the data in, and whether and how to group and summarize the data.

You work with a single table at a time in this lesson. In the next lesson you learn how to use multiple tables. The table used to illustrate this lesson is shown in Figure 23-1 and is created from the following code:

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;

INSERT INTO ‘table1’ (‘id’, ‘description’, ‘code’) VALUES
(101, ‘abc’, 99),
(102, ‘a’‘bc’, 15),
(103, ‘a’‘bc’, 15),
(104, ‘a’‘bc’, 15),
(105, ‘def’, 23),
(106, ‘ghi’, 23),
(107, ‘jkl’, 15),
(108, ‘mno’, 15),
(109, ‘pqr’, 23),
(110, ‘stu’, 42),
(111, ‘vwx’, 42),
(112, ‘yza’, 42),
(118, ‘efg’, 99);

Using the SELECT Command

The easiest form of the SELECT command is to select all fields and rows from a single table:

SELECT * FROM ‘table1’;

The asterisk (*) indicates that all fields are to be selected and FROM ‘table1’ tells which table to use. By default all ...

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.