PHP 5/MySQL Programming- P67 ppsx

5 242 0
PHP 5/MySQL Programming- P67 ppsx

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

Thông tin tài liệu

CREATE TABLE phoneList ( id INT PRIMARY KEY, firstName VARCHAR(15), lastName VARCHAR (15), email VARCHAR(20), phone VARCHAR(15) ); You can think of fields as being much like variables, but while PHP is easy-going about what type of data is in a variable, SQL is very picky about the type of data in fields. In order to create an efficient database, MySQL needs to know exactly how many bytes of memory to set aside for every single field in the database. It does this primarily by requiring the database designer to specify the type and size of every field in each table. Table 9.2 lists a few of the primary data types sup- ported by MySQL. While the data types listed in Table 9.2 are by far the most commonly used, MySQL supports many others. Look in the online Help that ships with MySQL if you need a more specific data type. Other databases have a very similar list of data types. You might notice that it is unnecessary to specify the length of numeric types (although you can determine a maximum size for numeric types as well as the number of digits you want stored in float and double fields). The storage require- ments for numeric fields are based on the field type itself. TRICK 308 P H P 5 /M y S Q L P r o g r a m m i n g f o r t h e A b s o l u t e B e g i n n e r Data Type Description INT Standard integer +/– 2 billion (roughly) BIGINT Big integer +/– 9 x 10 ^18 th FLOAT Floating-point decimal number 38 digits DOUBLE Double-precision floating-point 308 digits CHAR(n) Text with n digits; if actual value is less than n, field is padded with trailing spaces VARCHAR(n) Text with n digits; trailing spaces are automatically culled DATE Date in YYYY-MM-DD format TIME Time in HH:MM:SS format YEAR Year in YYYY format TABLE 9.2 COMMON D ATA T YPES IN M Y SQL Working with String Data in MySQL Text values are usually stored in VARCHAR fields. These fields must include the number of characters allocated for the field. Both CHAR and VARCHAR fields have fixed lengths. The primary difference between them is what happens when the field contains a value shorter than the specified length. Assume you declared a CHAR field to have a length of 10 with the following SQL segment: firstName VARCHAR(10); Later you store the value ‘Andy’ into the field. The field actually contains ‘Andy ’. (That is, Andy followed by six spaces.) CHAR fields pad any remaining characters with spaces. The VARCHAR field type removes any padded spaces. The VARCHAR field type is the one you use most often to store string data. Finishing the CREATE TABLE Statement Once you understand field data types, the CREATE TABLE syntax makes a lot of sense. Only a few more details to understand: • Use a pair of parentheses to indicate the field list once you specify CREATE TABLE . 309 C h a p t e r 9U s i n g M y S Q L t o C r e a t e D a t a b a s e s DETERMINING THE LENGTH OF A VARCHAR FIELD Data design is both a science and an art. Determining the appropriate length for your text fields is one of the oldest problems in data. If you don’t allocate enough room for your text data, you can cause a lot of prob- lems for your users. I once taught a course called CLT SD WEB PRG because the database that held the course names didn’t have enough room for the actual course name (Client-Side Web Programming). My students renamed it the Buy a Vowel course. However, you can’t make every text field a thousand characters long, either, because it would waste system resources. If you have a field that will usually con- tain only five characters and you allocate one hundred characters, the drive still requires room for the extra 95 characters. If your database has thousands of entries, this can be a substantial cost in drive space. In a distributed environment, you have to wait for those unnecessary spaces to come across limited bandwidth. It takes experimentation and practice to determine the appropriate width for your string fields. Test your application with real users so you can be sure you’ve made the right decision. • Name each field and follow it with its type (and length, if it’s a CHAR or VARCHAR). • Separate the fields with commas. • Put each field on its own line and indent the field definitions. You don’t have to, but I prefer to, because these practices make the code much easier to read and debug. Creating a Primary Key You might be curious about the very first field in the phone list database. Just to refresh your memory, the line that defines that field looks like this: id INT PRIMARY KEY, Most database tables have some sort of field that holds a numeric value. This spe- cial field is called the primary key . You can enter the code presented so far directly into the MySQL program. You can see the code and its results in Figure 9.6. Using the DESCRIBE Command to Check a Table’s Structure Checking the structure of a table can be helpful, especially if somebody else cre- ated it or you don’t remember exactly its field types or sizes. The DESCRIBE com- mand lets you view a table structure. 310 P H P 5 /M y S Q L P r o g r a m m i n g f o r t h e A b s o l u t e B e g i n n e r IN THE REAL WORLD A simple database could theoretically go without a primary key, but such fields are so important to more sophisticated databases that you might as well start putting them in. It’s traditional to put a primary key in every table. In chapter 11, “Data Normalization,” you learn more about the relational data model. In that discussion you learn how keys build powerful databases and more about creating proper primary keys. In fact, the adventure program you’ve already seen heavily relies on a key field even though there’s only one table in the database. Inserting Values Once you’ve created a table, you can begin adding data to it. The INSERT com- mand is the primary tool for adding records. INSERT INTO phoneList VALUES ( 0, ‘Andy’, ‘Harris’, ‘aharris@cs.iupui.edu’, ‘123-4567’ ); The INSERT statement allows you to add a record into a database. The values must be listed in exactly the same order the fields were defined. Each value is sepa- rated by a comma, and all VARCHAR and CHAR values must be enclosed in single quo- tation marks. If you have a large amount of data to load, you can use the LOAD DATA command. This command accepts a tab-delimited text file with one row per record and fields separated by tabs. It then loads that entire file into the database. This is often the fastest way to load a database with test data. The following line loads data from a file called addresses.txt into the phoneList table: LOAD DATA LOCAL INFILE “addresses.txt” INTO TABLE phoneList; Figure 9.7 shows the MySQL tool after I have added one record to the table. 311 C h a p t e r 9U s i n g M y S Q L t o C r e a t e D a t a b a s e s FIGURE 9.6 This is the MySQL command-line tool after I created the phoneList table. Selecting Results Of course, you want to see the results of all your table-building activities. If you want to see the data in a table, you can use the SELECT command. This is perhaps the most powerful command in SQL, but its basic use is quite simple. Use this command to see all of the data in the phoneList table: SELECT * FROM phoneList This command grabs all fields of all records of the phoneList database and dis- plays them in table format. Figure 9.8 shows what happens after I add a SELECT statement to get the results. 312 P H P 5 /M y S Q L P r o g r a m m i n g f o r t h e A b s o l u t e B e g i n n e r IN THE REAL WORLD As you are building a database, populate the database with test values. Don’t use actual data at this point, because your database will not work correctly until you’ve messed with it for some time. However, your test values should be reflective of the kinds of data your database will house. This helps you spot cer- tain problems like fields that are too small or missing. FIGURE 9.7 MySQL tells you the operation succeeded, but you don’t get a lot more information. . VARCHAR(20), phone VARCHAR(15) ); You can think of fields as being much like variables, but while PHP is easy-going about what type of data is in a variable, SQL is very picky about the type of

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

Từ khóa liên quan

Mục lục

  • PHP 5 / MySQL Programming for the Absolute Beginner

    • Cover

    • Contents

    • Introduction

    • Chapter 1: Exploring the PHP Environment

    • Chapter 2: Using Variables and Input

    • Chapter 3: Controlling Your Code with Conditions and Functions

    • Chapter 4: Loops and Arrays

    • Chapter 5: Better Arrays and String Handling

    • Chapter 6: Working with Files

    • Chapter 7: Writing Programs with Objects

    • Chapter 8: XML and Content Management Systems

    • Chapter 9: Using MySQL to Create Databases

    • Chapter 10: Connecting to Databases within PHP

    • Chapter 11: Data Normalization

    • Chapter 12: Building a Three-Tiered Data Application

    • Index

    • Team DDU

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan