Index
    Preface
      What This Book Is About
      What You Need to Know
      How This Book Is Organized
      How to Use This Book
      Conventions Used in This Book
      Using Code Examples
      How to Contact Us
      Web Site and Code Examples
      Acknowledgments
      Chapter 1.  Database Applications and the Web
      Section 1.1.  The Web
      Section 1.2.  Three-Tier Architectures
      Chapter 2.  The PHP Scripting Language
      Section 2.1.  Introducing PHP
      Section 2.2.  Conditions and Branches
      Section 2.3.  Loops
      Section 2.4.  Functions
      Section 2.5.  Working with Types
      Section 2.6.  User-Defined Functions
      Section 2.7.  A Working Example
      Chapter 3.  Arrays, Strings, and Advanced Data Manipulation in PHP
      Section 3.1.  Arrays
      Section 3.2.  Strings
      Section 3.3.  Regular Expressions
      Section 3.4.  Dates and Times
      Section 3.5.  Integers and Floats
      Chapter 4.  Introduction to Object-Oriented Programming with PHP 5
      Section 4.1.  Classes and Objects
      Section 4.2.  Inheritance
      Section 4.3.  Throwing and Catching Exceptions
      Chapter 5.  SQL and MySQL
      Section 5.1.  Database Basics
      Section 5.2.  MySQL Command Interpreter
      Section 5.3.  Managing Databases and Tables
      Section 5.4.  Inserting, Updating, and Deleting Data
      Section 5.5.  Querying with SQL SELECT
      Section 5.6.  Join Queries
      Section 5.7.  Case Study: Adding a New Wine
      Chapter 6.  Querying Web Databases
      Section 6.1.  Querying a MySQL Database Using PHP
      Section 6.2.  Processing User Input
      Section 6.3.  MySQL Function Reference
      Chapter 7.  PEAR
      Section 7.1.  Overview
      Section 7.2.  Core Components
      Section 7.3.  Packages
      Chapter 8.  Writing to Web Databases
      Section 8.1.  Database Inserts, Updates, and Deletes
      Section 8.2.  Issues in Writing Data to Databases
      Chapter 9.  Validation with PHP and JavaScript
      Section 9.1.  Validation and Error Reporting Principles
      Section 9.2.  Server-Side Validation with PHP
      Section 9.3.  JavaScript and Client-Side Validation
      Chapter 10.  Sessions
      Section 10.1.  Introducing Session Management
      Section 10.2.  PHP Session Management
      Section 10.3.  Case Study: Using Sessions in Validation
      Section 10.4.  When to Use Sessions
      Section 10.5.  PHP Session API and Configuration
      Chapter 11.  Authentication and Security
      Section 11.1.  HTTP Authentication
      Section 11.2.  HTTP Authentication with PHP
      Section 11.3.  Form-Based Authentication
      Section 11.4.  Protecting Data on the Web
      Chapter 12.  Errors, Debugging, and Deployment
      Section 12.1.  Errors
      Section 12.2.  Common Programming Errors
      Section 12.3.  Custom Error Handlers
      Chapter 13.  Reporting
      Section 13.1.  Creating a Report
      Section 13.2.  Producing PDF
      Section 13.3.  PDF-PHP Reference
      Chapter 14.  Advanced Features of Object-Oriented Programming in PHP 5
      Section 14.1.  Working with Class Hierarchies
      Section 14.2.  Class Type Hints
      Section 14.3.  Abstract Classes and Interfaces
      Section 14.4.  Freight Calculator Example
      Chapter 15.  Advanced SQL
      Section 15.1.  Exploring with SHOW
      Section 15.2.  Advanced Querying
      Section 15.3.  Manipulating Data and Databases
      Section 15.4.  Functions
      Section 15.5.  Automating Querying
      Section 15.6.  Table Types
      Section 15.7.  Backup and Recovery
      Section 15.8.  Managing Users and Privileges
      Section 15.9.  Tuning MySQL
      Chapter 16.  Hugh and Dave's Online Wines:A Case Study
      Section 16.1.  Functional and System Requirements
      Section 16.2.  Application Overview
      Section 16.3.  Common Components
      Chapter 17.  Managing Customers
      Section 17.1.  Code Overview
      Section 17.2.  Customer Validation
      Section 17.3.  The Customer Form
      Chapter 18.  The Shopping Cart
      Section 18.1.  Code Overview
      Section 18.2.  The Winestore Home Page
      Section 18.3.  The Shopping Cart Implementation
      Chapter 19.  Ordering and Shipping at the Online Winestore
      Section 19.1.  Code Overview
      Section 19.2.  Credit Card and Shipping Instructions
      Section 19.3.  Finalizing Orders
      Section 19.4.  HTML and Email Receipts
      Chapter 20.  Searching and Authentication in the Online Winestore
      Section 20.1.  Code Overview
      Section 20.2.  Searching and Browsing
      Section 20.3.  Authentication
      Appendix A.  Linux Installation Guide
      Section A.1.  Finding Out What's Installed
      Section A.2.  Installation Overview
      Section A.3.  Installing MySQL
      Section A.4.  Installing Apache
      Section A.5.  Installing PHP
      Section A.6.  What's Needed for This Book
      Appendix B.  Microsoft Windows Installation Guide
      Section B.1.  Installation Overview
      Section B.2.  Installing with EasyPHP
      Section B.3.  What's Needed for This Book
      Appendix C.  Mac OS X Installation Guide
      Section C.1.  Getting Started
      Section C.2.  Installing MySQL
      Section C.3.  Setting Up Apache and PHP
      Section C.4.  What's Needed for This Book
      Appendix D.  Web Protocols
      Section D.1.  Network Basics
      Section D.2.  Hypertext Transfer Protocol
      Appendix E.  Modeling and Designing Relational Databases
      Section E.1.  The Relational Model
      Section E.2.  Entity-Relationship Modeling
      Appendix F.  Managing Sessions in theDatabase Tier
      Section F.1.  Using a Database to Keep State
      Section F.2.  PHP Session Management
      Section F.3.  MySQL Session Store
      Appendix G.  Resources
      Section G.1.  Client Tier Resources
      Section G.2.  Middle-Tier Resources
      Section G.3.  Database Tier Resources
      Section G.4.  Security and Cryptography Resources
      Appendix H.  The Improved MySQL Library
      Section H.1.  New Features
      Section H.2.  Getting Started
      Section H.3.  Using the New Features
    Colophon
    Copyright



 

Previous Section  < Day Day Up >  Next Section

5.4 Inserting, Updating, and Deleting Data

There are four major statements for working with data in SQL: SELECT, INSERT, DELETE, and UPDATE. We describe the latter three statements in this section. SELECT is covered it in its own section later in this chapter.

5.4.1 Inserting Data

Having created a database and the accompanying tables and indexes, the next step is to insert data into the tables. Inserting a row can follow two different approaches. We show both approaches by inserting the same data for a new customer, Lucy Williams.

Consider an example of the first approach using the customer table:

INSERT INTO customer VALUES (1,'Williams','Lucy','E',3,

'272 Station St','Carlton North','VIC','3054',12,'(613)83008460',

'2002-07-02');

The statement creates a new row in the customer table, then the first value 1 is inserted into the first attribute, cust_id. The second value 'Williams' is inserted into the second attribute surname, 'Lucy' into firstname, and so on.

The number of values inserted is the same as the number of attributes in the table (and an error is generated if the number of values doesn't match the number of attributes). If you don't want to supply data for an attribute, you can include NULL instead of a value (as long as the attribute isn't defined as NOT NULL and NULL is valid for that data type). For example, to create a partial customer row, you could use:

INSERT INTO customer VALUES (1,'Williams','Lucy',NULL,3,

NULL,NULL,NULL,NULL,12,NULL,NULL);

To create an INSERT statement using this first format, you need to know the ordering of the attributes in the table. You can discover the table structure by typing SHOW COLUMNS FROM customer into the MySQL command interpreter or by reviewing the CREATE TABLE statement used to create the table. The SHOW statement is described in detail in Chapter 15.

If you want to insert more than one row, you can write more than one INSERT statement. Alternatively, you can write one INSERT statement and separate each row with a comma. Consider an example that uses the latter approach and inserts the details for two customers:

INSERT INTO customer VALUES (1,'Williams','Lucy','E',3,

'272 Station St','Carlton North','VIC','3054',12,'(613)83008460',

'2002-07-02'), (2,'Williams','Selina','J',4,'12 Hotham St',

'Collingwood','VIC','3066',12,'(613)99255432','1980-06-03');

This approach is the fastest way to insert data into MySQL.

Data can also be inserted using a second approach. Consider this example:

INSERT INTO customer SET cust_id = 1, surname = 'Williams', 

   firstname = 'Lucy', initial='E', title_id=3, 

   address='272 Station St', city='Carlton North',

   state='VIC', zipcode='3054', country_id=12,

   phone='(613)83008460', birth_date='2002-07-10';

In this approach, the attribute name is listed, followed by the assignment operator (=) and then the value to be assigned. This approach doesn't require the same number of values as attributes, and it also allows arbitrary ordering of the attributes. This can save you lots of typing when a row has many attributes but is sparsely populated with values. For example, to create a partial customer row, you could use:

INSERT INTO customer SET cust_id = 653, surname = 'Williams',

   firstname = 'Lucy', title_id = 3, country_id = 12;

The first approach can actually be varied to function in a similar way to the second by including parenthesized attribute names before the VALUES keyword. For example, you can create an incomplete customer row with:

INSERT INTO customer (cust_id, surname, city) 

  VALUES (1, 'Williams','North Carlton');

When inserting data, non-numeric attributes must be enclosed in either single or double quotes. If a string contains single quotation marks, the string can be enclosed in double quotation marks. For example, consider the string "Steve O'Dwyer". Likewise, strings containing double quotation marks can be enclosed in single quotation marks. An alternative approach is to escape the quotation character by using a backslash character; for example, as in the string `Steve O\'Dwyer'. Numeric values can also be enclosed in quotes but they aren't mandatory.

There are other ways to insert data in addition to those discussed here. For example, a popular variation is to insert data from another table using a query or to insert data from a formatted text file. These two approaches and other variants are discussed in Chapter 15.

5.4.1.1 Defaults

If you don't include the value for an attribute, it is set to the DEFAULT value if it's supplied in the table definition or to NULL otherwise (if it is valid for the attribute to be NULL). If an attribute is defined as being NOT NULL and does not have a DEFAULT value, the value that's set depends on the attribute type; for example, integer attributes are set to 0 (which causes an auto_increment attribute to be populated with a new identifier, as discussed next) and strings to the empty string. However, rather than worry about what happens, we recommend that you define a DEFAULT value for any attribute that you don't always want to list in an INSERT statement. Even if you want NULL to be inserted when nothing is provided, you can define it as the DEFAULT.

Inserting NULL into a TIMESTAMP (or any date or time type) attribute stores the current date and time. Inserting 0 into a TIMESTAMP attribute doesn't have the same effect as inserting NULL, because 0 is a valid date and time combination.

5.4.1.2 Auto-increment

MySQL provides a non-standard SQL auto_increment modifier that makes management of primary keys easy; most other database servers provide a similar non-standard feature. The goal of using auto_increment is to make sure that each row in your table has a unique primary key so that you can refer to it in other tables; as discussed previously, this is a common requirement in databases.

The following is a simple table definition that uses the auto_increment feature to create a unique value for the primary key:

CREATE TABLE names (

  id smallint(4) NOT NULL auto_increment,

  name varchar(20),

  PRIMARY KEY (id)

);

You can insert data into this table by setting only the name attribute:

INSERT INTO names SET name = "Bob";

In this example, the id is set to the next available identifier because the default value of an integer attribute is 0 and this invokes the auto_increment feature.

In general, when you insert NULL (or zero) as the next value for an attribute with the auto_increment modifier, the value that is stored is the maximum value + 1. For example, if there are already 10 rows in the names table with id values of 1 to 10, inserting a row with NULL as the id (or not providing an id and invoking the default behavior) creates a row with an id value of 11.

The auto_increment modifier is a useful feature when you want to insert data with a unique primary key, but don't want to have to read the data first to determine the next available value to use. As we show you later in Chapter 8, this also helps avoid concurrency problems (and, therefore, the need for locking) when several users are using the same database. The disadvantage is that it's a proprietary MySQL feature. However, we also show you how to develop a generic approach to managing identifiers in Chapter 9 and we also show you how it's done with PHP's PEAR DB.

Only one attribute in a table can have the auto_increment modifier.

The result of an auto_increment modifier can be checked with the MySQL-specific function last_insert_id( ). For the previous example, you can check which id was created with the statement:

SELECT last_insert_id( );

This statement reports:

+------------------+

| last_insert_id( ) |

+------------------+

|               11 |

+------------------+

1 row in set (0.04 sec)

You can see that the new row has id=11. To check an identifier value, the function should be called immediately after inserting the new row.

5.4.2 Deleting Data

The DELETE statement removes data from tables. For example, the following deletes all data in the customer table but doesn't remove the table:

DELETE FROM customer;

A DELETE statement with a WHERE clause can remove specific rows; WHERE clauses are frequently used in querying, and they are explained later in Section 5.5. Consider a simple example:

DELETE FROM customer WHERE cust_id = 1;

This deletes the customer with a cust_id value of 1. Consider another example:

DELETE FROM customer WHERE surname = 'Smith';

This removes all rows for customers with a surname value of Smith.

5.4.3 Updating Data

Data can be updated using a similar syntax to the INSERT statement. Consider an example:

UPDATE customer SET state = upper(state);

This replaces the string values of all state attributes with the same string in uppercase. The function upper( ) is one of many MySQL functions discussed in Chapter 15.

You can update more than one attribute in a statement. For example, to set both the state and city to uppercase, use:

UPDATE customer SET state = upper(state), city = upper(city);

The UPDATE statement is also often used with the WHERE clause. For example:

UPDATE customer SET surname = 'Smith' WHERE cust_id = 7;

This updates the surname attribute of customer #7. Consider a second example:

UPDATE customer SET zipcode = '3001' WHERE city = 'Melbourne';

This updates the zipcode of all rows with a city value Melbourne.

After an UPDATE is completed, MySQL returns the number of rows that were changed. If MySQL finds that a value doesn't need to be changed (because it's already set to the value you want to change it to), it isn't updated and isn't included in the count that's returned.

    Previous Section  < Day Day Up >  Next Section







    Copyright © 2010 | Domen maybe sale - bye this domen