11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

www.it-ebooks.infoCHAPTER 28 • MYSQL STORAGE ENGINES AND DATA TYPESinformal introduction. Instead, this section covers various features of this statement as they becomerelevant in future sections. No<strong>net</strong>heless, general usage will be demonstrated here. As an example, thefollowing creates the employees table discussed at the start of this chapter:CREATE TABLE employees (id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,firstname VARCHAR(25) NOT NULL,lastname VARCHAR(25) NOT NULL,email VARCHAR(45) NOT NULL,phone VARCHAR(10) NOT NULL,PRIMARY KEY(id));Keep in mind that a table must consist of at least one column. Also, you can always go back and altera table structure after it has been created. Later in this section, you’ll learn how this is accomplished viathe ALTER TABLE statement.You can also create a table regardless of whether you’re currently using the target database. Simplyprepend the table name with the target database name like so:database_name.table_nameConditionally Creating a TableBy default, <strong>MySQL</strong> generates an error if you attempt to create a table that already exists. To avoid thiserror, the CREATE TABLE statement offers a clause that can be included if you want to simply abort thetable-creation attempt if the target table already exists. For example, suppose you want to distribute anapplication that relies on a <strong>MySQL</strong> database for storing data. Because some users will download thelatest version as a matter of course for upgrading and others will download it for the first time, yourinstallation script requires an easy means for creating the new users’ tables while not causing unduedisplay of errors during the upgrade process. This is done via the IF NOT EXISTS clause. So, if you want tocreate the employees table only if it doesn’t already exist, do the following:CREATE TABLE IF NOT EXISTS employees (id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,firstname VARCHAR(25) NOT NULL,lastname VARCHAR(25) NOT NULL,email VARCHAR(45) NOT NULL,phone VARCHAR(10) NOT NULL,PRIMARY KEY(id));One oddity of this action is that the output does not specify whether the table was created. Bothvariations display the “Query OK” message before returning to the command prompt.Copying a TableIt’s a trivial task to create a new table based on an existing one. The following query produces an exactcopy of the employees table, naming it employees2:CREATE TABLE employees2 SELECT * FROM employees;549

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!