Page 395 - Beginning PHP 5.3
P. 395
Chapter 12: Introducing Databases and SQL
(The asterisk means “ all fields. ” ) You can also specify just the field or fields you want to retrieve:
mysql > SELECT name, color from fruit;
+-----------+--------+
| name | color |
+-----------+--------+
| banana | yellow |
| tangerine | orange |
| plum | purple |
+-----------+--------+
3 rows in set (0.00 sec)
To retrieve a selected row or rows, you need to introduce a WHERE clause at the end of the SELECT
statement. A WHERE clause filters the results according to the condition in the clause. You can use
practically any expression in a WHERE condition. Here are some simple WHERE clauses in action:
mysql > SELECT * from fruit WHERE name = ‘banana’;
+----+--------+--------+
| id | name | color |
+----+--------+--------+
| 1 | banana | yellow |
+----+--------+--------+
1 row in set (0.08 sec)
mysql > SELECT * from fruit WHERE id > = 2;
+----+-----------+--------+
| id | name | color |
+----+-----------+--------+
| 2 | tangerine | orange |
| 3 | plum | purple |
+----+-----------+--------+
2 rows in set (0.06 sec)
You build more complex SELECT queries and WHERE clauses in the next chapter.
Updating Data in a Table
You change existing data in a table with the UPDATE statement. As with the SELECT statement, you can
(and usually will) add a WHERE clause to specify exactly which rows you want to update. If you leave out
the WHERE clause, the entire table gets updated.
Here ’ s how to use UPDATE to change values in your fruit table:
mysql > UPDATE fruit SET name = ‘grapefruit’, color = ‘yellow’ WHERE id = 2;
Query OK, 1 row affected (0.29 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql > SELECT * from fruit;
+----+------------+--------+
| id | name | color |
+----+------------+--------+
| 1 | banana | yellow |
| 2 | grapefruit | yellow |
| 3 | plum | purple |
+----+------------+--------+
3 rows in set (0.00 sec)
357
9/21/09 9:11:13 AM
c12.indd 357
c12.indd 357 9/21/09 9:11:13 AM