Before you can start entering data, you need to define the table structure.. This involves deciding the following: • The name of the table • How many columns it will have • The name of e
Trang 1291
11 Click Add a new User, and repeat steps 4 through 8 to create a second user account called
psread This user will have much more restricted privileges, so when you get to step 7, check
only the SELECT option The password used for psread in the example files is K1y0mi$u
Creating a database table
Now that you have a database and dedicated user accounts, you can begin creating tables Lets begin by creating a table to hold the details of images, as shown in Figure 10-1 Before you can start entering data, you need to define the table structure This involves deciding the following:
• The name of the table
• How many columns it will have
• The name of each column
• What type of data will be stored in each column
• Whether the column must always have data in each field
• Which column contains the tables primary key
If you look at Figure 10-1, you can see that the table contains three columns: image_id (primary key), filename, and caption Because it contains details of images, thats a good name to use for the table Theres not much point in storing a filename without a caption, so every column must contain data Great! Apart from the data type, all the decisions have been made Ill explain the data types as we go along
Defining the images table
These instructions show how to define a table in phpMyAdmin If you prefer to use Navicat, SQLyog, or a different UI for MySQL, use the settings in Table 10-1
1 Launch phpMyAdmin, if its not already open, and select phpsols from the Database
drop-down menu in the left frame Type the name of the new table (images) in the field labeled
Create new table on database phpsols, and enter 3 as the Number of fields (As
mentioned before, phpMyAdmin refers to columns as fields What it means is how many fields
each record has.) Then click the Go button
2 The next screen is where you define the table Because the images table contains only three
columns, the options for each column are listed vertically When you define a table with more than three columns, the options are displayed horizontally There are a lot of options, but not all of them need to be filled in Table 10-1 lists the settings for the images table
Table 10-1 Settings for the images table
Field Type Length/Values Attributes Null Index AUTO_INCREMENT
Trang 2292
The first column, image_id, is defined as type INT, which stands for integer Its attribute is set to UNSIGNED, which means that only positive numbers are allowed Its index is declared as PRIMARY, and the AUTO_INCREMENT check box is selected, so MySQL automatically inserts in this column the next available number (starting at 1) whenever a new record is inserted The next column, filename, is defined as type VARCHAR with a length of 25 This means it accepts up to 25 characters of text
The final column, caption, is also VARCHAR with a length of 120, so it accepts up to 120 characters of text
The Null check box for all columns is deselected, so they must always contain something.
However, that “something” can be as little as an empty string Ill describe the column types in more detail in “Choosing the right column type in MySQL” later in this chapter
The following screenshot shows the options after they have been set in phpMyAdmin:
3 Toward the bottom of the screen is an option for Storage Engine This determines the format
used internally by MySQL to store the database files MyISAM is the default storage engine in MySQL 3.23 through 5.1 However, it has been announced that an improved version of the InnoDB storage engine will become the default in MySQL 5.5 At the time of this writing, many
Trang 3293
hosting companies dont support InnoDB or offer it only on premium hosting plans Ill explain the differences between these storage engines in Chapter 16 In the meantime, use MyISAM Converting from one storage engine to another is very simple
4 When you have finished, click the Save button at the bottom of the screen
If you click Go instead of Save, phpMyAdmin adds an extra column for you to define If this happens, give the new column a dummy name, and set the Type option to INT You can then delete the extra column by clicking the Delete icon (a red cross) in the relevant row in the Structure table
that appears in the next screen
5 The next screen displays the SQL query that phpMyAdmin used to define the images table
Beneath that, youll see the structure of the table displayed like this:
Dont be alarmed by the fact that Collation displays latin1_swedish_ci MySQL was originally developed
in Sweden, and Swedish uses the same sort order as English (and Finnish) The underlining of image_id indicates that its the tables primary key To change any settings, click the pencil-like icon in the appropriate row This opens a version of the previous screen and allows you to change the values If you
made a complete mess and want to start again, click the Drop tab at the top right of the screen, and
confirm that you want to drop the table (In SQL, delete refers only to records You drop a table or a
database.)
Inserting records into a table
Now that you have a table, you need to put some data into it Eventually, youll need to build your own content management system using HTML forms, PHP, and SQL; but the quick and easy way to do it is with phpMyAdmin
Using phpMyAdmin to insert records manually
These instructions show how to add individual records to the images table through the phpMyAdmin interface
1 If phpMyAdmin is still displaying the structure of the images table as at the end of the previous
section, skip to step 2 Otherwise, launch phpMyAdmin, and select the phpsols database
from the drop-down menu in the left frame Then click the Structure icon alongside images, as
shown in the following screenshot:
Trang 4294
The breadcrumb trail at the top of the main frame provides the context for the tabs across the head
of the page The Structure tab at the top left of the preceding screenshot refers to the structure of the phpsols database At the moment, it contains only one table, images To access the structure of
an individual table, click the Structure icon alongside its name Use your mouse pointer to reveal tooltips for each icon Some, such as Browse, are grayed out because there are no records in the table
2 Click the Insert tab in the center top of the page This displays the following screen, ready for
you to insert up to two records:
3 The forms display the names and details of each column You can ignore the Function fields
MySQL has a large number of functions that you can apply to the values being stored in your
Trang 5295
table Youll learn more about them in the following chapters The Value field is where you enter
the data you want to insert in the table
Because you have defined image_id as AUTO_INCREMENT, MySQL inserts the next available
number automatically So you must leave the image_id Value field blank Fill in the next two
Value fields as follows:
• filename: basin.jpg
• caption: Water basin at Ryoanji temple, Kyoto
4 In the second form, leave the Value field for image_id blank, and fill in the next two fields like
this:
• filename: fountains.jpg
• caption: Fountains in central Tokyo
Normally, the Ignore check box is automatically deselected when you add values to the
second form, but deselect it if necessary
5 Click Go The SQL used to insert the records is displayed at the top of the page, together with
a report that two rows have been inserted Ill explain the basic SQL commands in the
remaining chapters, but studying the SQL that phpMyAdmin displays is a good way to learn how to build your own queries SQL is closely based on human language, so it isnt all that difficult to learn
6 Click the Browse tab at the top left of the page You should now see the first two entries in the
images table, as shown here:
As you can see, MySQL has automatically inserted 1 and 2 in the image_id fields
You could continue typing out the details of the remaining six images, but lets speed things up a bit by using a SQL file that contains all the necessary data
Loading the images records from a SQL file
Because the primary key of the images table has been set to AUTO_INCREMENT, its necessary to drop the original table and all its data The SQL file does this automatically and builds the table from scratch These instructions assume that phpMyAdmin is open at the page in step 6 of the previous section
1 If youre happy to overwrite the data in the images table, skip to step 2 However, if you have
entered data that you dont want to lose, copy your data to a different table Click the
Operations tab at the top of the page, type the name of the new table in the blank field in the
section titled Copy table to (database.table), and click Go The following screenshot
shows the settings for copying the images table to images_backup:
Trang 6296
2 After clicking Go, you should see confirmation that the table has been copied The
breadcrumb trail at the top of the page indicates that phpMyAdmin is still in the images table,
so you can proceed to step 2, even though you have a different page onscreen
3 Click the Import tab at the top right of the page In the next screen, click the Browse (or Choose File) button in File to import, and navigate to images.sql in the ch10 folder Leave
all options at their default setting, and click Go at the foot of the page
4 phpMyAdmin drops the original table, creates a new version, and inserts all the records When
you see confirmation that the file has been imported, click the Browse button at the top left of
the page You should now see the same data as shown in Figure 10-1 at the beginning of the chapter
If you open the images.sql in a text editor, youll see that it contains the SQL commands that create the images table and populate it with data This is how the table is built:
DROP TABLE IF EXISTS `images`;
CREATE TABLE IF NOT EXISTS `images` (
`image_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`filename` varchar(25) NOT NULL,
`caption` varchar(120) NOT NULL,
PRIMARY KEY (`image_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
Trang 7297
Importing data from a SQL file like this is how you transfer data from your local testing environment to the remote server where your website is located Assuming that your hosting company provides phpMyAdmin
to administer your remote database, all you need to do to transfer the data is to launch the version of
phpMyAdmin on your remote server, click the Import tab, select the SQL file on your local computer, and click Go
The next section describes how to create the SQL file
Creating a SQL file for backup and data transfer
MySQL doesnt store your database in a single file that you can simply upload to your website Even if you find the right files (on Windows, theyre located in C:\Program Files\MySQL\MySQL Server 5.1\data), youre likely to damage them unless the MySQL server is turned off Anyway, most hosting companies wont permit you to upload the raw files because it would also involve shutting down their server, causing a great deal of inconvenience for everyone
Nevertheless, moving a database from one server to another is very easy All it involves is creating a
backup dump of the data and loading it into the other database with phpMyAdmin or any other database
administration program The dump is a text file that contains all the necessary SQL commands to populate
an individual table or even an entire database elsewhere phpMyAdmin can create backups of your entire MySQL server, individual databases, selected tables, or individual tables To keep things simple, these instructions show you how to back up only a single database
1 In phpMyAdmin, select the phpsols database from the drop-down menu in the navigation
frame If the database was already selected, click the Database: phpsols breadcrumb at the
top of the screen, as shown here:
2 Select Export from the tabs along the top of the screen
3 The rather fearsome looking screen shown in Figure 10-6 opens In spite of all the options, you
need to concern yourself with only a few
• The Export section on the left of the screen lists all the tables in your database Click
Select All, and leave the radio buttons on the default SQL
• If the database has never been transferred to the other server before, the only option that
you need to set on the right side of the screen is the drop-down menu labeled SQL export
compatibility If the other server is running MySQL 3.23, choose MYSQL323 If the other
server is running MySQL 4.0, choose MYSQL40 Otherwise, choose NONE
• If the database has already been transferred on a previous occasion, select Add DROP
TABLE in the Structure section The existing contents of each table are dropped and are
replaced with the data in the backup file
Trang 8298
Figure 10-6 phpMyAdmin offers a wide range of choices when exporting data from MySQL
4 Make sure the check box labeled Save as file at the bottom of the screen is selected The
default setting in File name template is DB , which automatically gives the backup file
the same name as your database So, in this case, it becomes phpsols.sql If you add anything after the final double underscore, phpMyAdmin adds this to the name For instance,
Trang 9299
you might want to indicate the date of the backup, so you could add 2011-11-11 for a backup
made on November 11, 2011 The file would then be named phpsols2011-11-11.sql
5 If your database contains a lot of data, select a compression format from one of the radio
buttons at the bottom of the page When you import the file to another server, phpMyAdmin automatically decompresses it
6 Click Go, and save the SQL file to your local hard disk You now have a backup that can be
used to transfer the contents of your database to another server
The file created by phpMyAdmin contains the SQL commands only to create and populate the database tables It does not include the command to create the database This means you can import the tables into any database It does not need to have the same name as the one in your local testing environment
Choosing the right data type in MySQL
You may have received a bit of a shock when selecting Type for the image_id column phpMyAdmin lists
all available data types—there are nearly 40 in MySQL 5.1 Rather than confuse you with unnecessary details, Ill explain just the most commonly used You can find full details of all data types in the MySQL documentation at http://dev.mysql.com/ doc/refman/5.1/en/data-types.html
Storing text
The difference between the main text data types boils down to the maximum number of characters that can be stored in an individual field, the treatment of trailing spaces, and whether you can set a default value
• CHAR: A fixed-length string You must specify the required length in the Length/Values field
The maximum permitted value is 255 Internally, strings are right-padded with spaces to the specified length, but the trailing spaces are stripped when you retrieve the value You can define a default
• VARCHAR: A variable-length string You must specify the maximum number of characters you
plan to use (in phpMyAdmin, enter the number in the Length/Values field) Prior to MySQL
5.0, the limit was 255 This was increased to 65,535 in MySQL 5.0 If a string is stored with trailing spaces, they are preserved on retrieval Accepts a default value
• TEXT: Stores text up to a maximum of 65,535 characters (approximately 50% longer than this chapter) Cannot define a default value
TEXT is convenient because you dont need to specify a maximum size (in fact, you cant) Although the maximum length of VARCHAR is the same as TEXT in MySQL 5.0 and later, other factors may limit the actual amount that can be stored
Keep it simple: use VARCHAR for short text items and TEXT for longer ones
Trang 10300
Storing numbers
The most frequently used numeric column types are as follows:
• INT: Any whole number (integer) between –2,147,483,648 and 2,147,483,647 If the column is declared as UNSIGNED, the range is from 0 to 4,294,967,295
• FLOAT: A floating-point number You can optionally specify two comma-separated numbers to limit the range The first number specifies the maximum number of digits, and the second specifies how many of those digits should come after the decimal point Since PHP will format numbers after calculation, I recommend that you use FLOAT without the optional parameters
• DECIMAL: A number with a fraction containing a fixed number of digits after the decimal point When defining the table, you need to specify the maximum number of digits and how many of those digits should come after the decimal point In phpMyAdmin, enter the numbers
separated by a comma in the Length/Values field For example, 6,2 permits numbers in the
range from –9999.99 to 9999.99 If you dont specify the size, the decimal fraction is truncated when values are stored in this type of column
The difference between FLOAT and DECIMAL is accuracy Floating-point numbers are treated as approximate values and are subject to rounding errors (for a detailed explanation, see http://dev.mysql.com/doc/refman/5.1/en/problems-with-float.html)
Use DECIMAL to store currencies However, its important to note that prior to MySQL 5.0.3, the DECIMAL data type was stored as a string, so could not be used with SQL functions, such as SUM(), to perform calculations inside the database If your remote server is running an older version of MySQL, store currencies in an INT column as cents; for pounds, use pence Then use PHP to divide the result by 100, and format the currency as desired Better still, move to a server that runs MySQL 5.0 or higher
Dont use commas or spaces as the thousands-separator Apart from numerals, the only characters permitted in numbers are the negative operator (-) and the decimal point (.)
Storing dates and times
MySQL stores dates in one format only: YYYY-MM-DD Its the standard approved by the ISO (International Organization for Standardization) and avoids the ambiguity inherent in different national conventions Ill return to the subject of dates in Chapter 14 The most important column types for dates and times are as follows:
• DATE: A date stored as YYYY-MM-DD The range is 1000-01-01 to 9999-12-31
• DATETIME: A combined date and time displayed in the format YYYY-MM-DD HH:MM:SS
• TIMESTAMP: A timestamp (normally generated automatically by the computer) Legal values range from the beginning of 1970 to partway through January 2038