1. Trang chủ
  2. » Công Nghệ Thông Tin

Phát triển web với PHP và MySQL - p 24 pot

10 309 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 519,03 KB

Nội dung

Table 8.10 shows the TEXT and BLOB types. The maximum length of a TEXT field in characters is the maximum size in bytes of files that could be stored in that field. TABLE 8.10 TEXT and BLOB Types Maximum Length Type (Characters) Description TINYBLOB 2 8 -1 A tiny binary large object (BLOB) field (that is, 255) TINYTEXT 2 8 -1 A tiny TEXT field (that is, 255) BLOB 2 16 -1 A normal sized BLOB field (that is, 65,535) TEXT 2 16 -1 A normal sized TEXT field (that is, 65,535) MEDIUMBLOB 2 24 -1 A medium-sized BLOB field (that is, 16,777,215) MEDIUMTEXT 2 24 -1 A medium-sized TEXT field (that is, 16,777,215) LONGBLOB 2 32 -1 A long BLOB field (that is, 4,294,967,295) LONGTEXT 2 32 -1 A long TEXT field (that is, 4,294,967,295) Table 8.11 shows the ENUM and SET types. T ABLE 8.11 SET and ENUM Types Maximum Type Values in Set Description ENUM(‘value1’, 65535 Columns of this type can only hold one of ‘value2’, ) the values listed or NULL. SET(‘value1’, 64 Columns of this type can hold a set of the ‘value2’, ) specified values or NULL. Creating Your Web Database C HAPTER 8 8 CREATING YOUR WEB DATABASE 205 11 7842 CH08 3/6/01 3:38 PM Page 205 Further Reading For more information, you can read about setting up a database at the MySQL online manual at http://www.mysql.com/. Next Now that you know how to create users, databases, and tables, you can concentrate on interact- ing with the database. In the next chapter, we’ll look at how to put data in the tables, how to update and delete it, and how to query the database. Using MySQL P ART II 206 11 7842 CH08 3/6/01 3:38 PM Page 206 CHAPTER 9 Working with Your MySQL Database 12 7842 CH09 3/6/01 3:36 PM Page 207 Using MySQL P ART II 208 In this chapter, we’ll discuss Structured Query Language (SQL) and its use in querying data- bases. We’ll continue developing the Book-O-Rama database by seeing how to insert, delete, and update data, and how to ask the database questions. Topics we will cover include • What is SQL? • Inserting data into the database • Retrieving data from the database • Joining tables • Updating records from the database • Altering tables after creation • Deleting records from the database • Dropping tables We’ll begin by talking about what SQL is and why it’s a useful thing to understand. If you haven’t set up the Book-O-Rama database, you’ll need to do that before you can run the SQL queries in this chapter. Instructions for doing this are in Chapter 8, “Creating Your Web Database.” What Is SQL? SQL stands for Structured Query Language. It’s the most standard language for accessing rela- tional database management systems (RDBMS). SQL is used to store and retrieve data to and from a database. It is used in database systems such as MySQL, Oracle, PostgreSQL, Sybase, and Microsoft SQL Server among others. There’s an ANSI standard for SQL, and database systems such as MySQL implement this stan- dard. They also typically add some bells and whistles of their own. The privilege system in MySQL is one of these. You might have heard the phrases Data Definition Languages (DDL), used for defining data- bases, and Data Manipulation Languages (DML), used for querying databases. SQL covers both of these bases. In Chapter 8, we looked at data definition (DDL) in SQL, so we’ve already been using it a little. You use DDL when you’re initially setting up a database. You will use the DML aspects of SQL far more frequently because these are the parts that we use to store and retrieve real data in a database. 12 7842 CH09 3/6/01 3:36 PM Page 208 Inserting Data into the Database Before you can do a lot with a database, you need to store some data in it. The way you will most commonly do this is with the SQL INSERT statement. Recall that RDBMSs contain tables, which in turn contain rows of data organized into columns. Each row in a table normally describes some real-world object or relationship, and the column values for that row store information about the real-world object. We can use the INSERT statement to put rows of data into the database. The usual form of an INSERT statement is INSERT [INTO] table [(column1, column2, column3, )] VALUES (value1, value2, value3, ); For example, to insert a record into Book-O-Rama’s Customers table, you could type insert into customers values (NULL, “Julie Smith”, “25 Oak Street”, “Airport West”); You can see that we’ve replaced table with the name of the actual table we want to put the data in, and the values with specific values. The values in this example are all enclosed in double quotes. Strings should always be enclosed in pairs of single or double quotes in MySQL. (We will use both in this book.) Numbers and dates do not need quotes. There are a few interesting things to note about the INSERT statement. The values we specified will be used to fill in the table columns in order. If you want to fill in only some of the columns, or if you want to specify them in a different order, you can list the specific columns in the columns part of the statement. For example, insert into customers (name, city) values (“Melissa Jones”, “Nar Nar Goon North”); This approach is useful if you have only partial data about a particular record, or if some fields in the record are optional. You can also achieve the same effect with the following syntax: insert into customers set name=”Michael Archer”, address=”12 Adderley Avenue”, city=”Leeton”; You ’ll also notice that we specified a NULL value for the customerid column when adding Julie Smith and ignored that column when adding the other customers. You might recall that when we set the database up, we created customerid as the primary key for the Customers table, so this might seem strange. However, we specified the field as AUTOINCREMENT. This means that, if Working with Your MySQL Database C HAPTER 9 9 W ORKING WITH YOUR MYSQL DATABASE 209 12 7842 CH09 3/6/01 3:36 PM Page 209 we insert a row with a NULL value or no value in this field, MySQL will generate the next num- ber in the autoincrement sequence and insert it for us automatically. This is pretty useful. You can also insert multiple rows into a table at once. Each row should be in its own set of brackets, and each set of brackets should be separated by a comma. We’ve put together some simple sample data to populate the database. This is just a series of simple INSERT statements that use this multirow insertion approach. The script that does this can be found on the CD accompanying this book in the file \chapter9\book_insert.sql. It is also shown in Listing 9.1. LISTING 9.1 book_insert.sql —SQL to Populate the Tables for Book-O-Rama use books; insert into customers values (NULL, “Julie Smith”, “25 Oak Street”, “Airport West”), (NULL, “Alan Wong”, “1/47 Haines Avenue”, “Box Hill”), (NULL, “Michelle Arthur”, “357 North Road”, “Yarraville”); insert into orders values (NULL, 3, 69.98, “02-Apr-2000”), (NULL, 1, 49.99, “15-Apr-2000”), (NULL, 2, 74.98, “19-Apr-2000”), (NULL, 3, 24.99, “01-May-2000”); insert into books values (“0-672-31697-8”, “Michael Morgan”, “Java 2 for Professional Developers”, 34.99), (“0-672-31745-1”, “Thomas Down”, “Installing Debian GNU/Linux”, 24.99), (“0-672-31509-2”, “Pruitt, et al.”, “Sams Teach Yourself GIMP in 24 Hours”, 24.99), (“0-672-31769-9”, “Thomas Schenk”, “Caldera OpenLinux System Administration Unleashed”, 49.99); insert into order_items values (1, “0-672-31697-8”, 2), (2, “0-672-31769-9”, 1), (3, “0-672-31769-9”, 1), (3, “0-672-31509-2”, 1), (4, “0-672-31745-1”, 3); insert into book_reviews values (“0-672-31697-8”, “Morgan’s book is clearly written and goes well beyond most of the basic Java books out there.”); Using MySQL P ART II 210 12 7842 CH09 3/6/01 3:36 PM Page 210 You can run this script by piping it through MySQL as follows: >mysql -h host -u bookorama -p < book_insert.sql Retrieving Data from the Database The workhorse of SQL is the SELECT statement. It’s used to retrieve data from a database by selecting rows that match specified criteria from a table. There are a lot of options and differ- ent ways to use the SELECT statement. The basic form of a SELECT is SELECT items FROM tables [ WHERE condition ] [ GROUP BY group_type ] [ HAVING where_definition ] [ ORDER BY order_type ] [LIMIT limit_criteria ] ; We’ll talk about each of the clauses of the statement. First of all, though, let’s look at a query without any of the optional clauses, one that selects some items from a particular table. Typically, these items are columns from the table. (They can also be the results of any MySQL expressions. We’ll discuss some of the more useful ones later in this section.) This query lists the contents of the name and city columns from the Customers table: select name, city from customers; This query has the following output, assuming that you’ve entered the sample data from Listing 9.1: + + + | name | city | + + + | Julie Smith | Airport West | | Alan Wong | Box Hill | | Michelle Arthur | Yarraville | | Melissa Jones | Nar Nar Goon North | | Michael Archer | Leeton | + + + As you can see, we’ve got a table which contains the items we selected—name and city—from the table we specified, Customers. This data is shown for all the rows in the Customer table. You can specify as many columns as you like from a table by listing them out after the select keyword. You can also specify some other items. One useful one is the wildcard operator, *, Working with Your MySQL Database C HAPTER 9 9 W ORKING WITH YOUR MYSQL DATABASE 211 12 7842 CH09 3/6/01 3:36 PM Page 211 which matches all the columns in the specified table or tables. For example, to retrieve all columns and all rows from the order_items table, we would use select * from order_items; which will give the following output: + + + + | orderid | isbn | quantity | + + + + | 1 | 0-672-31697-8 | 2 | | 2 | 0-672-31769-9 | 1 | | 3 | 0-672-31769-9 | 1 | | 3 | 0-672-31509-2 | 1 | | 4 | 0-672-31745-1 | 3 | + + + + Retrieving Data with Specific Criteria In order to access a subset of the rows in a table, we need to specify some selection criteria. You can do this with a WHERE clause. For example, select * from orders where customerid = 3; will select all the columns from the orders table, but only the rows with a customerid of 3. Here’s the output: + + + + + | orderid | customerid | amount | date | + + + + + | 1 | 3 | 69.98 | 0000-00-00 | | 4 | 3 | 24.99 | 0000-00-00 | + + + + + The WHERE clause specifies the criteria used to select particular rows. In this case, we have selected rows with a customerid of 3. The single equal sign is used to test equality—note that this is different from PHP, and it’s easy to become confused when you’re using them together. In addition to equality, MySQL supports a full set of operators and regular expressions. The ones you will most commonly use in WHERE clauses are listed in Table 9.1. Note that this is not a complete list—if you need something not listed here, check the MySQL manual. Using MySQL P ART II 212 12 7842 CH09 3/6/01 3:36 PM Page 212 TABLE 9.1 Useful Comparison Operators for WHERE Clauses Operator Name Example Description (If Applicable) = equality customerid = 3 Tests whether two values are equal > greater than amount > 60.00 Tests whether one value is greater than another < less than amount < 60.00 Tests whether one value is less than another >= greater than amount >= 60.00 Tests whether one value is greater or equal than or equal to another <= less than or amount <= 60.00 Tests whether one value is less than equal or equal to another != or <> not equal quantity != 0 Tests whether two values are not equal IS NOT address is not Tests whether field actually NULL null contains a value IS NULL address is null Tests whether field does not contain a value BETWEEN amount between Tests whether a value is greater or 0 and 60.00 equal to a minimum value and less than or equal to a maximum value IN city in Tests whether a value is in a (“Carlton”, “Moe”) particular set NOT IN city not in Tests whether a value is not in (“Carlton”, a set “Moe”) LIKE pattern match name like Checks whether a value matches (“Fred %”) a pattern using simple SQL pattern matching NOT LIKE pattern match name not like Checks whether a value doesn’t (“Fred %”) match a pattern REGEXP regular name regexp Checks whether a value matches a expression regular expression The last three lines in the table refer to LIKE and REGEXP. These are both forms of pattern matching. Working with Your MySQL Database C HAPTER 9 9 W ORKING WITH YOUR MYSQL DATABASE 213 12 7842 CH09 3/6/01 3:36 PM Page 213 LIKE uses simple SQL pattern matching. Patterns can consist of regular text plus the % (per- cent) character to indicate a wildcard match to any number of characters and the _ (underscore) character to wildcard match a single character. In MySQL, these matches are not case sensi- tive. For example, ‘Fred %’ will match any value beginning with ‘fred ‘. The REGEXP keyword is used for regular expression matching. MySQL uses POSIX regular expressions. Instead of REGEXP, you can also use RLIKE, which is a synonym. POSIX regular expressions are also used in PHP. You can read more about them in Chapter 4, “String Manipulation and Regular Expressions.” You can test multiple criteria in this way and join them with AND and OR. For example, select * from orders where customerid = 3 or customerid = 4; Retrieving Data from Multiple Tables Often, to answer a question from the database, you will need to use data from more than table. For example, if you wanted to know which customers placed orders this month, you would need to look at the Customers table and the Orders table. If you also wanted to know what, specifically, they ordered, you would also need to look at the Order_Items table. These items are in separate tables because they relate to separate real-world objects. This is one of the principles of good database design that we talked about in Chapter 7, “Designing Your Web Database.” To put this information together in SQL, you must perform an operation called a join. This simply means joining two or more tables together to follow the relationships between the data. For example, if we want to see the orders that customer Julie Smith has placed, we will need to look at the Customers table to find Julie’s CustomerID, and then at the Orders table for orders with that CustomerID. Although joins are conceptually simple, they are one of the more subtle and complex parts of SQL. Several different types of join are implemented in MySQL, and each is used for a differ- ent purpose. Simple Two-Table Joins Let’s begin by looking at some SQL for the query about Julie Smith we just talked about: select orders.orderid, orders.amount, orders.date from customers, orders where customers.name = ‘Julie Smith’ and customers.customerid = orders.customerid; Using MySQL P ART II 214 12 7842 CH09 3/6/01 3:36 PM Page 214 . quantity | + + + + | 1 | 0-6 7 2-3 169 7-8 | 2 | | 2 | 0-6 7 2-3 176 9-9 | 1 | | 3 | 0-6 7 2-3 176 9-9 | 1 | | 3 | 0-6 7 2-3 150 9-2 | 1 | | 4 | 0-6 7 2-3 174 5-1 | 3 | + + + + Retrieving Data with Specific Criteria In. “15-Apr-2000”), (NULL, 2, 74.98, “19-Apr-2000”), (NULL, 3, 24. 99, “01-May-2000”); insert into books values (“ 0-6 7 2-3 169 7-8 ”, “Michael Morgan”, “Java 2 for Professional Developers”, 34.99), (“ 0-6 7 2-3 174 5-1 ”,. OpenLinux System Administration Unleashed”, 49.99); insert into order_items values (1, “ 0-6 7 2-3 169 7-8 ”, 2), (2, “ 0-6 7 2-3 176 9-9 ”, 1), (3, “ 0-6 7 2-3 176 9-9 ”, 1), (3, “ 0-6 7 2-3 150 9-2 ”, 1), (4, “ 0-6 7 2-3 174 5-1 ”,

Ngày đăng: 06/07/2014, 19:20