Thursday, June 26, 2008

How to upgrade MySQL?


New versions of MySQL are released periodically, and you can upgrade from one version of MySQL to a newer version. Upgrading information is provided in the MySQL manual at dev.mysql.com/doc/refman/5.0/en/upgrade. html. However, there are special considerations when upgrading. As a precaution, it is wise to back up your current databases, including the grant tables in the mysql database, before upgrading. MySQL recommends that you do not skip versions. If you want to upgrade from one version to a version more than one version newer, such as from MySQL 4.0 to MySQL 5.0, you should upgrade to the next version first. After that version is working correctly, you can upgrade to the next version.
And so on. In other words, upgrade from 4.0 to 4.1, then from 4.1 to 5.0. Occasionally, incompatible changes are introduced in new versions of MySQL. Some releases introduce changes to the structure of the grant tables. For instance, MySQL 4.1 changed the method of encrypting passwords, requiring a longer password field in the grant tables. After upgrading to the newer version, you should run the mysql_upgrade script. It checks your files, repairing them if needed, and upgrades the system tables if needed. Before MySQL version 5.0.19, the mysql_upgrade script does not run on Windows; it runs only on Unix. On Windows, you can run a script called mysql_fix_privileges_tables with MySQL versions prior to 5.0.19. The script upgrades the system tables but does not perform the complete table check and repair that mysql_upgrade performs.

Friday, June 13, 2008

How to Restore Your Data?


At some point, one of your database tables might become damaged and unusable. It’s unusual, but it happens. For instance, a hardware problem or an unexpected shutdown of the computer can cause corrupted tables. Sometimes an anomaly in the data that confuses MySQL can cause corrupt tables. In some cases, a corrupt table can cause your MySQL server to shut down.
Here is a typical error message that signals a corrupted table:
Incorrect key file for table: ‘tablename’.
You can replace the corrupted table(s) with the data stored in a backup copy. In some cases, the database might be lost completely. For instance, if the computer where your database resides breaks down and can’t be fixed, your current database is lost, but your data isn’t gone forever. You can replace the broken computer with a new computer and restore your database from a backup copy.
You can replace your current database table(s) with the database stored in a backup copy. The backup copy contains a snapshot of the data as it was when the copy was made. Any changes to the database since the backup copy was made are not included; you have to re-create those changes manually. Again, if you access MySQL through an IT department or through a Web hosting company, you need to ask the MySQL administrator to restore your database from a backup. If you’re the MySQL administrator, you can restore it yourself.
As I describe in Chapter 4, you build a database by creating the database and then adding tables to the database. The backup created by the mysqldump utility is a file that contains all the SQL statements necessary to rebuild the tables, but it does not contain the statements needed to create the database. Your database might not exist, or it could exist with one or more corrupted tables. You can restore the entire database or any single table. Follow these steps to restore a single table:
  1. If the table currently exists, delete the table with the following SQL query: DROP TABLE tablename where tablename is the table that you want to delete.
  2. Point your browser at mysql_send.php. For a description of mysql_send.php.
  3. Copy the CREATE query for the table from the backup file into the form in the browser window. For instance, choose EditCopy and EditPaste.
  4. Type the name of the database in which you are restoring the table. The form shows where to type the database name.
  5. Click Submit. A new Web page shows the results of the query.
  6. Click New Query.
  7. Copy an INSERT query for the table from the backup file into the form in the browser window. For instance, choose EditCopy and EditPaste.
  8. Type the name of the database in which you are restoring the table. The form shows where to type the database name.
  9. Click Submit. A new Web page shows the results of the query.
  10. Click New Query.
  11. Repeat Steps 7–10 until all the INSERT queries from the backup file have been sent.
If you have so many INSERT queries for the table that sending them one by one would take forever — or if there are just a lot of tables — you can send all the queries in the backup file at once. First, you may need to edit the backup file, as follows:
  1. Open the backup file in a text editor.
  2. Locate the line that shows the Server Versions.
  3. If you want to rebuild an entire database, add the following statement after the line located in Step 2: CREATE DATABASE IF NOT EXISTS databasename
  4. After the line in Step 3, add a line specifying which database to add the tables to: USE databasename
  5. Check the blocks of statements that rebuild the tables. If you do not want to rebuild a table, comment out the lines that rebuild the table by adding -- (two hyphens) in front of each line.
  6. Check the INSERT lines for each table. If you do not want to add data to any tables, comment out the lines that INSERT the data.
  7. Save the edited backup file.
After the backup file contains the statements that you want to use to rebuild your database or table(s), you need to perform a few more steps.
On Linux, Unix, and Mac:
  1. Change to the bin subdirectory in the directory where MySQL is installed. Type a cd command to change to the correct directory. For instance, type cd /usr/local/mysql/bin.
  2. Type the command that sends the SQL queries in the backup file: mysql -u accountname -p <>
Change to the bin subdirectory in the directory where MySQL is installed.
    • a. Open a command prompt window. For instance, choose StartAll ProgramsAccessoriesCommand Prompt.
    • b. Type a cd command to change to the correct directory.
For instance, type cd c:\Program Files\MySQL\MySQL Server 5.0\bin.

Type the command that sends the SQL queries in the backup file: mysql -u accountname -p <>

Thursday, June 12, 2008

How to Back Up Your Data?

You need to have at least one copy of your valuable database. Disasters occur rarely, but they do occur. The computer where your database is stored can break down and lose your data, the computer file can become corrupted, the building can burn down, and so on. Backup copies of your database guard against data loss from such disasters.
You should have at least one backup copy of your database, stored in a location that is separate from the copy that is currently in use. More than one copy — perhaps as many as three — is usually a good idea:
  • Store one copy in a handy location, perhaps even on the same computer, to quickly replace a working database that has been damaged. _ Store a second copy on another computer in case the computer breaks down, and the first backup copy isn’t available.
  • Store a third copy in a different physical location, for that remote chance that the building burns down. If the second backup copy is stored via a network on a computer at another physical location, this third copy isn’t needed.
If you don’t have access to a computer offsite where you can back up your database, you can copy your backup to a portable medium, such as a CD or DVD, and store it offsite. Certain companies will store your computer media at their location for a fee, or you can just put the media in your pocket and take it home.
If you use MySQL on someone else’s computer, such as the computer of your employer or a Web hosting company, the people who provide your access are responsible for backups. They should have automated procedures in place that make backups of your database. When evaluating a Web hosting company, ask about their backup procedures. You want to know how often backup copies are made and where they are stored. If you aren’t confident that your data is safe, you can discuss changes or additions to the backup procedures. If you are the MySQL administrator, you are responsible for making backups. MySQL provides a program called mysqldump that you can use to make backup copies. The mysqldump program creates a text file that contains all the SQL statements needed to re-create your entire database. The file contains the CREATE statements for each table and INSERT statements for each row of data in the tables. You can restore your database by executing the set of MySQL statements. You can restore it in its current location, or you can restore it on another computer if necessary.
Follow these steps to make a backup copy of your database in Linux, in Unix, or on a Mac:
  1. Change to the bin subdirectory in the directory where MySQL is installed. For instance, type cd /usr/local/mysql/bin.
  2. Type the following: mysqldump—user=accountname—password=password databasename >path/backupfilename ,where
    • accountname is the name of the MySQL account that you’re using to back up the database
    • password is the password for the account
    • databasename is the name of the database that you want to back up
    • path/backupfilename is the path to the directory where you want to store the backups and the filename the SQL output will be stored in The account that you use needs to have select permission. If the account doesn’t require a password, you can leave out the entire password option. You can type the command on one line, without pressing Enter. Or you can type a backslash (\), press Enter, and continue the command on another line. For example, to back up the PetCatalog database, the command might be mysqldump—user=root—password=secret PetCatalog \ >/usr/local/mysql/backups/PetCatalogBackup Note: With Linux or Unix, the account that you are logged into must have permission to write a file into the backup directory.
To make a backup copy of your database in Windows, follow these steps:
  1. Open a command prompt window. For instance, choose StartAll ProgramsAccessoriesCommand prompt.
  2. Change to the bin subdirectory in the directory where MySQL is installed. For instance, type cd c:\Program Files\MySQL\MySQL Server 5.0\bin.
  3. Type the following: mysqldump—user=accountname—password=password databasename >path\backupfilename, where
    • accountname is the name of the MySQL account that you’re using to back up the database
    • password is the password for the account
    • databasename is the name of the database that you want to back up
    • path\backupfilename is the path to the directory where you want to store the backups and the filename the SQL output will be stored in The account that you use needs to have select permission. If the account does not require a password, you can leave out the entire password option. You must type the mysqldump command on one line without pressing Enter. For example, to back up the PetCatalog database, the command might be mysqldump—user=root PetCatalog >PetCatalogBackup Backups should be made at certain times — at least once per day. If your database changes frequently, you might want to back up more often. For example, you might want to back up to the backup directory hourly but back up to another computer once a day.

How to Remove accounts and permissions?


To remove an account, you can use the DROP USER query, which was added in MySQL 4.1.1, as follows:

DROP USER accountname@hostname, accountname@hostname, ...

You must be using an account that has DELETE privileges on the mysql database to execute the DROP USER query.
The behavior of DROP USER has changed through MySQL versions. As of MySQL 5.0.2, it removes the account and all records related to the account, including records that give it permissions on specific databases or tables. However, before MySQL 5.0.2, DROP USER drops only accounts with no privileges. Therefore, in older versions, you must remove all the privileges from an account, including database or table permissions, before you can drop it.
To remove permissions, use the REVOKE query. The general format is

REVOKE permission (columns) ON tablename FROM accountname@hostname

You need to fill in the following information:
  • permission (columns): You must list at least one permission. You can remove each permission from one or more columns by listing the column name in parentheses following the permission. If no column name is listed, the permission is removed from all columns in the table(s). You can list as many permissions/columns as needed, separated by commas. For instance, a REVOKE query might start like this: REVOKE select (firstName,lastName), update, insert (birthdate) ...
  • tablename: Indicate which tables the permission is being removed from. At least one table is required. You can list several tables, separated by commas. The possible values for tablename are
    • tablename: The entire table named tablename in the current database. You can use an asterisk (*) to mean all tables. If you use an asterisk when no current database is selected, the privilege will be revoked on all tables in all databases.
    • databasename.tablename: The entire table named tablename in databasename. You can use an asterisk (*) for either the database name or the table name to mean all. Using . revokes the permission on all tables in all databases.
  • accountname@hostname: The account is identified by the accountname and the hostname as a pair. If an account exists with the specified account name but a different hostname, the REVOKE query will fail, and you will receive an error message. You can remove all the permissions for an account with the following REVOKE query: REVOKE all ON . FROM accountname@hostname

How to change permissions?


You can see the current permissions for an account with the following query:

SHOW GRANTS ON accountname@hostname

The output is a GRANT query that would create the current account. It shows all the current permissions. If you do not include the ON clause, you see the current permissions for the account that issued the SHOW GRANTS query. You can change permissions for an account with the GRANT query, which has the following general format:

GRANT permission (columns) ON tablename TO accountname@hostname IDENTIFIED BY ‘password’

You can also create a new account or change a password with the GRANT query. You need to fill in the following information:
  • permission (columns): You must list at least one permission. You can limit each permission to one or more columns by listing the column name in parentheses following the permission. If no column name is listed, the permission is granted on all columns in the table(s). You can list as many permissions and columns as needed, separated by commas. For instance, a GRANT query might start with this: GRANT select (firstName,lastName), update, insert (birthdate) ...
    • tablename: This indicates which tables the permission is granted on. At least one table is required. You can list several tables, separated by commas. The possible values for tablename are
    • tablename: The entire table named tablename in the current database. You can use an asterisk (*) to mean all tables in the current database. If you use an asterisk and no current database is selected, the privilege will be granted to all tables on all databases.
    • databasename.tablename: The entire table named tablename in databasename. You can use an asterisk (*) for either the database name or the table name to mean all. Using . grants the permission on all tables in all databases.
  • accountname@hostname: If the account already exists, it is given the indicated permissions. If the account doesn’t exist, it’s added. The account is identified by the accountname and the hostname as a pair. If an account exists with the specified account name but a different hostname, the existing account is not changed; a new one is created.
  • password: This is the password that you’re adding or changing. A password is not required. If you don’t want to add or change a password for this account, leave out the phrase IDENTIFIED BY ‘password’. The GRANT query to add a new account for use in the PHP programs for the PetCatalog database might be GRANT select ON PetCatalog.* TO phpuser@localhost IDENTIFIED BY ‘A41!14a!’

How to add and change SQL passwords?


You can add or change a password for an existing account with the SET PASSWORD query, as follows:

SET PASSWORD FOR username@hostname = PASSWORD(‘password’)

The account is set to password for the account username@hostname. If the account currently has a password, the password is changed. You do not need to specify the FOR clause. If you do not, the password is set for the account you are currently using.
You can remove a password by sending the SET PASSWORD query with an empty password, as follows:

SET PASSWORD FOR username@hostname = PASSWORD(‘’)

How to Add Accounts?


The preferred way to access MySQL from PHP is to set up an account specifically for this purpose with only the permissions that are needed. In this section, I describe how to add accounts. If you’re using an account given to you by a company IT department or a Web hosting company, it might or might not have all the permissions needed to create an account. If it doesn’t, you won’t be able to successfully execute the query to add an account, and you’ll have to request a second account to use with PHP.
If you need to request a second account, get an account with restricted permission (if at all possible) because your Web database application will be more secure if the account used in your PHP programs doesn’t have more privileges than are necessary.
To create one or more users, you can use the CREATE USER query added to MySQL in version 5.0.2, as follows:

CREATE USER accountname@hostname IDENTIFIED BY ‘password’, accountname@hostname IDENTIFIED BY ‘password’,...

This query creates the specified new user account(s) with the specified password and no permissions. You do not need to specify a password. If you leave out IDENTIFIED BY ‘password’, the account is created with no password. You can add or change a password for the account at a later time. Adding passwords and permissions is discussed in the following sections. If you’re using a version of MySQL before 5.0.2, you must use a GRANT query to create an account. The GRANT query is described in the “Changing permissions” section.

Friday, May 23, 2008

Identifying what accounts currently exist


To see what accounts currently exist for your database, you need an account that has the necessary permissions. Try to execute the following query on a database named mysql:

SELECT * FROM user

You should get a list of all the accounts. However, if you’re accessing MySQL through your company or a Web hosting company, you probably don’t have the necessary permissions. In that case, you might get an error message like this:

No Database Selected

This message means that your account is not allowed to select the mysql database. Or you might get an error message saying that you don’t have SELECT permission. Even though this message is annoying, it’s a sign that the company has good security measures in place. However, it also means that you can’t see what privileges your account has. You must ask your MySQL administrator or try to figure it out yourself by trying queries and seeing whether you’re allowed to execute them.

The MySQL security database


When MySQL is installed, it automatically creates a database called mysql. All the information used to protect your data is stored in this database, including account names, hostnames, passwords, and permissions.
Permissions are stored in columns. The format of each column name is permission_priv. For instance, the column containing ALTER permissions is named alter_ priv. The value in each permission column is Y or N, meaning yes or no. So, for instance, in the user table (described in the following list), there would be a row for an account and a column for alter_priv. If the account field for alter_priv contains Y, the account can be used to execute an ALTER query. If alter_ priv contains N, the account doesn’t have permission to execute an ALTER query. The mysql database contains the following tables that store permissions:
  • user table: This table stores permissions that apply to all the databases and tables. It contains a row for each valid account that includes the column’s user name, hostname, and password. The MySQL server will reject a connection for an account that does not exist in this table.
  • db table: This table stores permissions that apply to a particular database. It contains a row for the database, which gives permissions to an account name and a hostname. The account must exist in the user table for the permissions to be granted. Permissions that are given in the user table overrule permissions in this table. For instance, if the user table has a row for the account designer that gives INSERT privileges, designer can insert into all the databases. If a row in the db table shows N for INSERT for the designer account in the PetCatalog database, the user table overrules it, and designer can insert in the PetCatalog database.
  • host table: This table controls access to a database depending on the host. The host table works with the db table. If a row in the db table has an empty field for the host, MySQL checks the host table to see whether the db has a row there. In this way, you can allow access to a db from some hosts but not from others. For instance, suppose you have two databases: db1 and db2. The db1 database has sensitive information, so you want only certain people to see it. The db2 database has information that you want everyone to see. If you have a row in the db table for db1 with a blank host field, you can have two rows for db1 in the host table. One row can give all permissions to users connecting from a specific host, whereas another row can deny privileges to users connecting from any other host.
  • tables_priv table: This table stores permissions that apply to specific tables.
  • columns_priv table: This table stores permissions that apply to specific columns.
You can see and change the tables in mysql directly if you’re using an account that has the necessary permissions. You can use SQL queries such as SELECT, INSERT, and UPDATE. If you’re accessing MySQL through your employer, a client, or a Web hosting company, it is unlikely that you will be given an account that has the necessary permissions.

Wednesday, May 7, 2008

Setting Up MySQL Accounts


An account is identified by the account name and the name of the computer allowed to access MySQL using this account. When you create a new account, you specify it as accountname@hostname. You can specify a password when you create an account or you can add a password later. You can set up permissions when you create an account or add permissions later. All the account information is stored in a database named mysql that is automatically created when MySQL is installed. To add a new account or change any account information, you must use an account that has the proper permissions on the mysql database.
You need at least one account to access the MySQL server. When MySQL is installed, it automatically sets up some accounts, including an account called root that has all permissions. If you have MySQL access through a company Web site or a Web hosting company, the MySQL administrator for the company should give you the account; the account is probably not named root, and it might or might not have all permissions.
In the rest of this section, I describe how to add and delete accounts and change passwords and permissions for accounts. If you have an account that you received from your company IT department or from a Web hosting company, you might receive an error when you try to send any or some of the GRANT or REVOKE queries described. If your account is restricted from performing any of the necessary queries, you need to request an account with more permissions or ask the MySQL administrator to add a new account or make the changes you need.

Taking a look at account permissions


MySQL uses account permissions to specify who can do what. Anyone using a valid account can connect to the MySQL server, but he or she can only do those things that are allowed by the permissions for the account. For example, an account might be set up so that users can select data but cannot insert or update data.
Permissions can be granted for particular databases, tables, or columns. For instance, an account can be set up that allows the user to select data from all the tables in the database but insert data into only one table and update only a single column in a specific table.
Permissions are added by using the GRANT query and removed by using the REVOKE query. The GRANT or REVOKE query must be sent using an account that has permission to execute GRANT or REVOKE statements in the database. If you attempt to send a GRANT query or a REVOKE query using an account without grant permission, you get an error message. For instance, if you try to grant permission to use a select query, and you send the query using an account that does not have permission to grant permissions, you might see the following error message: grant command denied Permissions can be granted or removed individually or all at once.
Permission &Description
ALL All permissions
ALTER Can alter the structure of tables
CREATE Can create new databases or tables
DELETE Can delete rows in tables
DROP Can drop databases or tables
FILE Can read and write files on the server
GRANT Can change the permissions on a MySQL account
INSERT Can insert new rows into tables
SELECT Can read data from tables
SHUTDOWN Can shut down the MySQL server
UPDATE Can change data in a table
USAGE No permissions
Granting ALL is not a good idea because it includes permissions for administrative operations, such as shutting down the MySQL server. You are unlikely to want anyone other than yourself to have such sweeping privileges.

Finding out about passwords


A password is set up for every account. If no password is provided for the account, the password is blank, which means that no password is required. MySQL doesn’t have any limit for the length of a password, but sometimes other software on your system limits the length to eight characters. If so, any characters after eight are dropped.
For extra security, MySQL encrypts passwords before it stores them. That means passwords are not stored in the recognizable characters that you entered. This security measure ensures that no one can look at the stored passwords and see what they are.
Unfortunately, some bad people out there might try to access your data by guessing your password. They use software that tries to connect rapidly in succession using different passwords — a practice called cracking. The following are some recommendations for choosing a password that is as difficult to crack as possible:
  • Use six to eight characters.
  • Include one or more of each of the following — uppercase letter, lowercase letter, number, and punctuation mark.
  • Do not use your account name or any variation of your account name.
  • Do not include any word in a dictionary, including foreign language dictionaries.
  • Do not include a name.
  • Do not use a phone number or a date.
A good password is hard to guess and easy to remember. If it’s too hard to remember, you might need to write it down, which defeats the purpose of having a password. One way to create a good password is to use the first characters of a favorite phrase. For instance, you could use the phrase “All for one! One for all!” to make this password:
Afo!Ofa!
This password doesn’t include any numbers, but you can fix that by using the
numeral 4 instead of the letter f. Then your password is
A4o!O4a!
Or you could use the number 1 instead of the letter o to represent one.
Then the password is
A41!14a!
This password is definitely hard to guess. Other ways to incorporate numbers into your passwords include substituting 1 (one) for the letter l or substituting 0 (zero) for the letter o.

Friday, May 2, 2008

Sun Asserts MySQL Will Remain Open Source


By Brian Prince

Marten Mickos, head of Sun Microsystems' database group, says MySQL will remain an open-source product.

After several days of blog posts and headlines, the dust that kicked up over Sun Microsystems' commitment to keeping MySQL open source seems to have settled.

At the center of the controversy were reports of plans to close-source backup features in Version 6.0 of the MySQL database, making them available only to subscription-paying users of its enterprise version. In an effort to clear the air, Marten Mickos, senior vice president of Sun's Database Group, responded to blog posts on Slashdot and elsewhere.

In an interview with eWEEK, he stated emphatically that Sun will not withhold or close-source any features that would make the MySQL community server less functional for users.

The core backup functionality and a backup API in Version 6.0 will be available to users of both the community and enterprise versions of the database, he said. However, the company plans to develop high-end add-ons such as encryption and compression solely for its MySQL Enterprise subscription customers, Mickos said.

Mickos calls MySQL the Ferrari of databases. Read why here.

“It is not a question of close-sourcing any existing code, nor anything in the core server,” Mickos said. “Everything MySQL has released under the GPL license continues to be under GPL, and the core MySQL server will always be under GPL, or some other free and open-source software [FOSS] license.”

Mickos said it has not been decided yet what license the add-ons will be released under. Sun, he added, was not part of the initial plans regarding the backup functionality—those discussions were taking place well before the acquisition by Sun earlier this year.

“At all times, because the main backup functionality goes into the core server under GPL, anyone can use the API and build their own add-ons or other modifications,” he said. “We are also offering them a convenient, low-cost option through our add-ons, but not forcing them or restricting them from building their own.”

Several MySQL users objected on blogs last week to talk of making key functionality available only to paying customers. It wasn’t the first time open-source advocates took MySQL to task for such moves; there was a similar, albeit more subdued, reaction when MySQL AB announced it was removing Enterprise source tarballs from ftp.mysql.com last August, analyst Matt Aslett noted.

“MySQL has been quick to respond to the criticism this time, and has been very open in explaining its strategy on user blogs, and the company does appear to have been able to stop the resentment from growing,” said Aslett, who is with The 451 Group. “It would be prudent for the company to prioritize deciding on which licenses it will use for the new functionality so that it can explain its strategy properly before doubt continues to spread.”

Mickos admitted the initial information was released awkwardly by the company and said he understood why some members of the open-source community were upset at first. This is why the company sought to aggressively address some of their concerns, he said.

“Open-source software is really just now reaching the radar of mainstream IT,” Mickos said. “There is still work to be done in formulating business models around open source, and so some degree of experimentation is essential. Keep in mind, open source itself began as an experiment in the software industry. So all vendors should not be afraid to continue to experiment both in software and in business models.”

Understanding account names and hostnames


Together, the account name and hostname (the name of the computer that is authorized to connect to the database) identify a unique account. Two accounts with the same name but different hostnames can exist and can have different passwords and permissions. However, you cannot have two accounts with the same name and the same hostname.
The MySQL server will accept connections from a MySQL account only when it is connecting from hostname. When you build the GRANT or REVOKE query (which I describe later in this chapter), you identify the MySQL account by using both the account name and the hostname in the following format: accountname@hostname (for instance, root@localhost). The MySQL account name is completely unrelated in any way to the Unix, Linux, or Windows user name (also sometimes called the login name). If you’re using an administrative MySQL account named root, it is not related to the Unix or Linux root login name. Changing the MySQL login name does not affect the Unix, Linux, or Windows login name — and vice versa.
MySQL account names and hostnames are defined as follows:
  • An account name can be up to 16 characters long. You can use special characters in account names, such as a space or a hyphen (-). However, you cannot use wildcards in the account name.
  • An account name can be blank. If an account exists in MySQL with a blank account name, any account name will be valid for that account. A user could use any account name to connect to your database, given that the user is connecting from a hostname that is allowed to connect to the blank account name and uses the correct password, if required. You can use an account with a blank name to allow anonymous users to connect to your database.
  • The hostname can be a name or an IP address. For example, it can be a name such as thor.mycompany.com or an IP (Internet protocol) address such as 192.163.2.33. The machine on which the MySQL server is installed is localhost.
  • The hostname can contain wildcards. You can use a percent sign (%) as a wildcard; % matches any hostname. If you add an account for george@%, someone using the account named george can connect to the MySQL server from any computer.
  • The hostname can be blank. A blank hostname is the same as using % for the hostname.
An account with a blank account name and a blank hostname is possible. Such an account would allow anyone to connect to the MySQL server by using any account name from any computer. An account with a blank name and a percent sign (%) for the hostname is the same thing. It is unlikely that you would want such an account. Such an account is sometimes installed when MySQL is installed, but it’s given no privileges, so it can’t do anything.

When MySQL is installed, it automatically installs an account with all privileges:
root@localhost. Depending on your operating system, this account may be installed without a password. Anyone who is logged in to the computer on which MySQL is installed can access MySQL and do anything to it by using the account named root. (Of course, root is a well-known account name, so this account is not secure. If you’re the MySQL administrator, you should add a password to this account immediately.)
On some operating systems, additional accounts besides root@localhost are automatically installed. For instance, on Windows, an account called root@% might be installed with no password protection. This root account with all privileges can be used by anyone from any machine. You should remove this account immediately or, at the very least, give it a password.

How to Control Access to Your MySQL Data?


You need to control access to the information in your database. You need to decide who can see the data and who can change it. Imagine what would happen if your competitors could change the information in your online product catalog or copy your list of customers — you’d be out of business in no time flat. Clearly, you need to guard your data. MySQL provides a security system for protecting your data. No one can access the data in your database without an account. Each MySQL account has the following attributes:
  • A name
  • A hostname — the machine from which the account can access the MySQL server
  • A password
  • A set of permissions
To access your data, someone must use a valid account name and know the password associated with that account. In addition, that person must be connecting from a computer that is permitted to connect to your database via that specific account.
After the user is granted access to the database, what he or she can do to the data depends on what permissions have been set for the account. Each account is either allowed or not allowed to perform an operation in your database, such as SELECT, DELETE, INSERT, CREATE, or DROP. The settings that specify what an account can do are privileges, or permissions. You can set up an account with all permissions, no permissions, or anything in between. For instance, for an online product catalog, you want the customer to be able to see the information in the catalog but not be able to change it. When a user attempts to connect to MySQL and execute a query, MySQL controls access to the data in two stages:
  1. Connection verification: MySQL checks the validity of the account name and password and checks whether the connection is coming from a host that is allowed to connect to the MySQL server by using the specified account. If everything checks out, MySQL accepts the connection.
  2. Request verification: After MySQL accepts the connection, it checks whether the account has the necessary permissions to execute the specified query. If it does, MySQL executes the query. Any query that you send to MySQL can fail either because the connection is rejected in the first step or because the query is not permitted in the second step. An error message is returned to help you identify the source of the problem.

Sunday, April 27, 2008

SQL injection attack hits hundreds of thousands of web page

An automated SQL injection attack has affected a large number of web sites - as in hundreds of thousands of pages - resulting in malware being downloaded to visitors' computers.

The attack appears to take advantage of features of Microsoft SQL Server, though according to security vendor F-Secure the problem lies in poor site coding, not in vulnerabilities in Microsoft's software. SQL injection is a well-known technique for attacking sites, and one that professional web developers should know they need to guard against.

Affected sites include some operated by the United Nations and the US, UK and Australian governments or their agencies.

According to F-Secure, the domains hosting the malicious content ultimately delivered by the hack are nmidahena.com, aspder.com and nihaorr1.com.

Some reports have suggested the problem is linked to an unpatched flaw in IIS that surfaced last week, but Microsoft has categorically denied that is the case. "We have also determined that these attacks are in no way related to Microsoft Security Advisory (951306)," wrote communications manager Bill Sisk in the Microsoft Security Response Center blog.

"The attacks are facilitated by SQL injection exploits and are not issues related to IIS 6.0, ASP, ASP.Net or Microsoft SQL technologies," he added.

Removing information


Keep the information in your database up to date by deleting obsolete information.
You can remove a row from a table with the DELETE query:

DELETE FROM tablename WHERE clause

Be extremely careful when using DELETE. If you use a DELETE query without a WHERE clause, it will delete all the data in the table. I mean all the data. I repeat, all the data. The data cannot be recovered. This function of the DELETE query is right at the top of my don’t-try-this-at-home list.
You can delete a column from a table by using the ALTER query:

ALTER TABLE tablename DROP columnname

Or you could remove the whole thing and start over again with

DROP TABLE tablename
or
DROP DATABASE databasename

Updating information


Changing information in an existing row is updating the information. For instance, you might need to change the address of a member because she has moved, or you might need to add a fax number that a member left blank when he originally entered his information.
The UPDATE query is straightforward:

UPDATE tablename SET column=value,column=value,...WHERE clause

In the SET clause, you list the columns to be updated and the new values to be inserted. List all the columns that you want to change in one query. Without a WHERE clause, the values of the column(s) would be changed in all rows. But with the WHERE clause, you can specify which rows to update.
For instance, to update an address in the Member table, use this query:

UPDATE Member SET street=”3333 Giant St”,
phone=”555-555-5555”
WHERE loginName=”bigguy”

Thursday, April 24, 2008

So You Think You Know SQL?

I was reading an old post by a buddy of mine about bad SQL being the cause of a lot of application problems and decided to weigh in my two cents.

A lot of developers get forced into writing SQL as part of their jobs. Should they be doing it? I don't think so. It's not necessarily the best of ideas, and in MOST cases should probably be avoided at all costs.

Besides, developers cannot be experts in every language or technology right? Something has got to give somewhere. It's usually their SQL skills that suffer. Developers are, sometimes, forced into situations where they have no choice but to write their own SQL. There is either no DBA, a DBA who isn't interested in helping developers with their queries, or a DBA who isn't even in the development loop (never a good sign). In these cases, developers may have to write their own SQL.

Sometimes developers have to know their limitations when it comes to writing queries, especially complex queries. I don't think a lot of developers do truly know their skill limitations. Yet, these intrepid souls will trudge on thinking they can write SQL just fine. When, in reality, they really and truly do not know the little tricks and tweaks that can make the SQL perform better.

I've seen it a thousand times. It's not an indictment of the developer, just a limitation of their skills that needs to be recognized.

Don't lose hope though, there are ways to combat this and make your SQL as good as it should be, or as good as it can be. What are these answers, then? Personally, I opt for something like Hibernate (Java) or Transfer (ColdFusion) to abstract my SQL for me. What does this mean? It means that my queries will be optimized and I can spend my time focused on developing the business logic rather than spending that time mired in persistence.

It also gives me the agility of being (most of the time) database agnostic. This lets us easily develop in one database locally, and port the same code to the server on a different database with minimal configuration changes. If ORMs are not an option for you and you have access to a good DBA, engage them. Talk to them and mine them for all the information they're worth. It's their job to know the database you're using and how to optimize queries. Make them earn their money by at least helping you write your queries, if not transferring the database functionality to them altogether (good luck).

None of these two options are viable? Well maybe you'll have to engage an outside consultancy to help you with your persistence layer optimizations, or pursue another path for optimizing your queries that has not been mentioned here. The bottom line is this: If you optimize your persistence today, then you'll have to spend less time dealing with it later when it causes you problems tomorrow. You may be able to write SQL, you may be able to do complex joins and create some wicked stored procedures, but are you a SQL expert? If so, then never mind this post. If not, then don't be afraid to swallow your pride and ask for help.

How to Use Join?


Combining tables side by side is a join. Tables are combined by matching data in a column — the column that they have in common. The combined results table produced by a join contains all the columns from both tables. For instance, if one table has two columns (memberID and height), and the second table has two columns (memberID and weight), a join results in a table with four columns: memberID (from the first table), height, memberID (from the second table), and weight.

The two common types of joins are an inner join and an outer join. The difference between an inner and outer join is in the number of rows included in the results table. The results table produced by an inner join contains only rows that existed in both tables. The combined table produced by an outer join contains all rows that existed in one table with blanks in the columns for the rows that did not exist in the second table. For instance, if table1 contains a row for Joe and a row for Sally, and table2 contains only a row for Sally, an inner join would contain only one row: the row for Sally. However, an outer join would contain two rows — a row for Joe and a row for Sally — even though the row for Joe would have a blank field for weight. The results table for the outer join contains all the rows for one table. If any of the rows for that table don’t exist in the second table, the columns for the second table are empty. Clearly, the contents of the results table are determined by which table contributes all its rows, requiring the second table to match it. Two kinds of outer joins control which table sets the rows and which match: a LEFT JOIN and a RIGHT JOIN. You use different SELECT queries for an inner join and the two types of outer joins. The following query is an inner join:

SELECT columnnamelist FROM table1,table2
WHERE table1.col2 = table2.col2
And these queries are outer joins:
SELECT columnnamelist FROM table1 LEFT JOIN table2
ON table1.col1=table2.col2
SELECT columnnamelist FROM table1 RIGHT JOIN table2
ON table1.col1=table2.col2

In all three queries, table1 and table2 are the tables to be joined. You can join more than two tables. In both queries, col1 and col2 are the names of the columns being matched to join the tables. The tables are matched based on the data in these columns. These two columns can have the same name or different names. The two columns must contain the same type of data.

How to Use UNION


UNION is used to combine the results from two or more select queries. The results from each query are added to the result set following the results of the previous query. The format of the UNION query is as follows:

SELECT query UNION ALL SELECT query ...

You can combine as many SELECT queries as you need. A SELECT query can include any valid SELECT format, including WHERE clauses, LIMIT clauses, and so on. The rules for the queries are
  • All the select queries must select the same number of columns.
  • The columns selected in the queries must contain the same type of data.
The result set will contain all the rows from the first query followed by all the rows from the second query and so on. The column names used in the result set are the column names from the first SELECT query. The series of SELECT queries can select different columns from the same table, but situations in which you want a new table with one column in a table followed by another column from the same table are unusual. It’s much more likely that you want to combine columns from different tables. For example, you might have a table of members who have resigned from the club and a separate table of current members. You can get a list of all members, both current and resigned, with the following query:

SELECT lastName,firstName FROM Member UNION ALL SELECT lastName,firstName FROM OldMember

The result of this query is the last and first names of all current members, followed by the last and first names of all the members who have resigned. Depending on how you organized your data, you might have duplicate names. For instance, perhaps a member resigned, and his name is in the OldMember table — but he joined again, so his name is added to the Member table. If you don’t want duplicates, don’t include the word ALL. If ALL is not included, duplicate lines are not added to the result.
You can use ORDER BY with each SELECT query, as I discuss in the previous section, or you can use ORDER BY with a UNION query to sort all the rows in the result set. If you want ORDER BY to apply to the entire result set, rather than just to the query that it follows, use parentheses as follows:

(SELECT lastName FROM Member UNION ALL
SELECT lastName FROM OldMember) ORDER BY lastName

The UNION statement was introduced in MySQL 4.0. It is not available in MySQL 3.

Sunday, April 20, 2008

Microsoft to Offer SQL Server 2005 SP3

Microsoft will release a third service pack for SQL Server 2005, just before the next version of the server software comes out.

Service Pack 3 is expected to come out after the release to manufacturing of SQL Server 2008, which is scheduled to happen in the third quarter this year.

Microsoft didn't reveal much about what the service pack would include, except to say in a Tuesday blog post that it will contain all cumulative updates to the software plus some additional fixes to bugs that customers have reported on MS Connect, a Microsoft Web site for customer feedback.

The development of a third service pack does not change the Incremental Servicing Model that Microsoft introduced last year. The model, unveiled last July, introduced a regular update process to SQL Server 2005. Since then, every two months Microsoft issues a cumulative update for SQL Server 2005 that includes all critical fixes that had been released during that time as well as updates for less urgent issues.

Customers like the predictability of the model, so Microsoft will continue using it, said Francois Ajenstat, director of SQL Server marketing for Microsoft, in a separate blog post. However, users also say that there's a need for a third service pack, so Microsoft plans to release one, he said. The company is announcing its plans now so that customers can plan for deployment, he said.

CodeGear delivers Delphi for PHP 2.0.


CodeGear, the developer tools arm of Borland Software, has upgraded its tool set for PHP developers.

The company announced Delphi for PHP 2.0 on April 14. Delphi for PHP is an IDE (integrated development environment) for rapidly building interactive Web applications using visual drag-and-drop design capabilities. The product also features a PHP component framework.

To read about the debugger CodeGear contributed to Eclipse, click here.

CodeGear officials said Delphi for PHP 2.0 features several enhancements, including HTML templates with embedded dynamic PHP; database support for MySQL, CodeGear InterBase, Microsoft SQL Server, Oracle, PostgreSQL, IBM Informix and DB2, and Sybase's SQL Anywhere, plus the ability to build rich data-driven Web applications without requiring database connectivity coding; an expanded and faster VCL (Visual Component Library) for PHP with support for popular PHP packages and libraries including the Zend Framework from Zend Technologies; productivity and performance enhancements including new error insight and source code formatting; and new PHP debugging features and integrated PHP performance profiling and tuning.

According to Michael Swindell, CodeGear's vice president of products, Version 2.0 of Delphi for PHP is a major advancement over the initial version, which introduced PHP developers to the productivity of a specialized IDE.

Yet, "perhaps the most significant advance is the new HTML template system, which enables PHP developers to seamlessly build rich PHP applications against HTML templates for design flexibility and easy customization with popular HTML tools," Swindell said.

Delphi for PHP 2.0 is available at an introductory price of $249 through the end of June 2008. Upgrades from Delphi for PHP 1.0 are currently $179.

Combining information from tables


In previous sections of this chapter, I assume that all the information you want is in a single table. However, you might want to combine information from different tables. You can do this easily in a single query. Two words can be used in a SELECT query to combine information from two or more tables:
  • UNION: Rows are retrieved from one or more tables and stored together, one after the other, in a single result. For example, if your query selected 6 rows from one table and 5 rows from another table, the result would contain 11 rows.
  • JOIN: The tables are combined side by side, and the information is retrieved from both tables.

Retrieving data from a specific source


Frequently, you don’t want all the information from a table. You want information from selected database objects, that is, rows. Three SQL words are frequently used to specify the source of the information:
  • WHERE: Allows you to request information from database objects with certain characteristics. For instance, you can request the names of members who live in California, or you can list only pets that are cats.
  • LIMIT: Allows you to limit the number of rows from which information is retrieved. For instance, you can request all the information from the first three rows in the table.
  • DISTINCT: Allows you to request information from only one row of identical rows. For instance, in the Login table, you can request loginName but specify no duplicate names, thus limiting the response to one record for each member. This would answer the question, “Has the member ever logged in?” rather than the question “How many times has the member logged in?”
The WHERE clause of the SELECT query enables you to make complicated selections. For instance, suppose your boss asks for a list of all the members whose last names begin with B, who live in Santa Barbara, and who have an 8 in either their phone or fax number. I’m sure there are many uses for such a list. You can get this list for your boss with a SELECT query by using a WHERE clause.
The basic format of the WHERE clause is

WHERE expression AND|OR expression AND|OR expression ...

expression specifies a value to compare with the values stored in the database. Only the rows containing a match for the expression are selected. You can use as many expressions as needed, each one separated by AND or OR. When you use AND, both of the expressions connected by the AND (that is, both the expression before the AND and the expression after the AND) must be true in order for the row to be selected. When you use OR, only one of the expressions connected by the OR must be true for the row to be selected. You can combine any of the expressions with ANDs and ORs. In some cases, you need to use parentheses to clarify the selection criteria. For instance, you can use the following query to answer your boss’s urgent need to find all people in the Member Directory whose names begin with B, who live in Santa Barbara, and who have an 8 in either their phone or fax number:

SELECT lastName,firstName FROM Member
WHERE lastName LIKE “B%”
AND city = “Santa Barbara”

AND (phone LIKE “%8%” OR fax LIKE “%8%”) Notice the parentheses in the last line. You would not get the results that your boss asked for without the parentheses. Without the parentheses, each connector would be processed in order from the first to the last, resulting in a list that includes all members whose names begin with B and who live in Santa Barbara and whose phone numbers have an 8 in them and all members whose fax numbers have an 8 in them, whether they live in Santa Barbara or not and whether their name begins with a B or not. When the last OR is processed, members are selected whose characteristics match the expression before the OR or the expression after the OR. The expression before the OR is connected to previous expressions by the previous ANDs and so does not stand alone, but the expression after the OR does stand alone, resulting in the selection of all members with an 8 in their fax number.

LIMIT specifies how many rows can be returned. The form for LIMIT is
LIMIT startnumber,numberofrows

The first row that you want to retrieve is startnumber, and the number of rows to retrieve is numberofrows. If startnumber is not specified, 1 is assumed. To select only the first three members who live in Texas, use this query:

SELECT * FROM Member WHERE state=”TX” LIMIT 3

Some SELECT queries will find identical records, but in this example you want to see only one — not all — of the identical records. To prevent the query from returning all identical records, add the word DISTINCT immediately after SELECT.

Retrieving data in a specific order


You might want to retrieve data in a particular order. For instance, in the Member table, you might want members organized in alphabetical order by last name. Or, in the Pet table, you might want the pets grouped by type of pet. In a SELECT query, ORDER BY and GROUP BY affect the order in which the data is delivered to you:
  • ORDER BY: To sort information, use the phrase ORDER BY columnname The data is sorted by columnname in ascending order. For instance, if columnname is lastName, the data is delivered to you in alphabetical order by the last name. You can sort in descending order by adding the word DESC before the column name. For example: SELECT * FROM Member ORDER BY DESC lastName
  • GROUP BY: To group information, use the following phrase: GROUP BY columnname The rows that have the same value of columnname are grouped together. For example, use this query to group the rows that have the same value as petType:
    • SELECT * FROM Pet GROUP BY petType
  • You can use GROUP BY and ORDER BY in the same query.

Retrieving specific information


To retrieve specific information, list the columns containing the information you want. For example:

SELECT columnname,columnname,columnname,... FROM tablename

This query retrieves the values from all the rows for the indicated column(s). For instance, the following query retrieves all the last names and first names stored in the Member table:

SELECT lastName,firstName FROM Member

You can perform mathematical operations on columns when you select them.
For example, you can use the following SELECT query to add two columns:

SELECT col1+col2 FROM tablename

Or you could use the following query:

SELECT price,price*1.08 FROM Pet

The result is the price and the price with the sales tax of 8 percent added.
You can change the name of a column when selecting it, as follows:

SELECT price,price*1.08 AS priceWithTax FROM Pet

The AS clause tells MySQL to give the name priceWithTax to the second column retrieved. Thus, the query retrieves two columns of data: price and priceWithTax.
In some cases, you don’t want to see the values in a column, but you want to know something about the column. For instance, you might want to know the lowest value in the column or the highest value in the column. For example, the query to find out the highest price in the Pet table is

SELECT MAX(price) FROM Pet

SQL words that look like MAX() and SUM(), with parentheses following the name, are functions. Some functions provide information about a column. Other functions change each value selected. For example, SQRT() returns the square root of each value in the column, and DAYNAME() returns the name of the day of the week for each value in a date column, rather than the actual date stored in the column. More than 100 functions are available for use in a SELECT query. For descriptions of all the functions, see the MySQL online manual at dev.mysql.com/doc/refman/5.0/en/functions.html.

Tuesday, April 8, 2008

Retrieving information from database

The only purpose in storing information is to have it available when you need it. A database lives to answer questions. What pets are for sale? Who are the members? How many members live in Arkansas? Do you have an alligator for sale? How much does a dragon cost? What is Goliath Smith’s phone number? And on and on. You use the SELECT query to ask the database questions.
The simplest, basic SELECT query is

SELECT * FROM tablename

This query retrieves all the information from the table. The asterisk (*) is a wildcard meaning all the columns.
The SELECT query can be much more selective. SQL words and phrases in the SELECT query can pinpoint the information needed to answer your question. You can specify what information you want, how you want it organized, and the source of the information:
  • You can request only the information (the columns) that you need to answer your question. For instance, you can request only the first and last names to create a list of members.
  • You can request information in a particular order. For instance, you can request that the information be sorted in alphabetical order.
  • You can request information from selected objects (the rows) in your table. For instance, you can request the first and last names for only those members whose addresses are in Florida.
In MySQL 4.1, MySQL added the ability to nest a SELECT query inside another query. The nested query is called a subquery. You can use a subquery in SELECT, INSERT, UPDATE, or DELETE queries or in SET clauses. A subquery can return a single value, a single row or column, or a table, which is used in the outer query. All the features of SELECT queries can be used in subqueries. See the MySQL online manual at dev.mysql.com/doc/refman/5.0/en/ subqueries.html for detailed information on using subqueries.

How to adding a bunch of data into database?

If you have a large amount of data to enter and it’s already in a computer file, you can transfer the data from the existing computer file to your MySQL database. The SQL query that reads data from a text file is LOAD. The LOAD query requires you to specify a database.

Because data in a database is organized in rows and columns, the text file being read must indicate where the data for each column begins and ends and where the end of a row is. To indicate columns, a specific character separates the data for each column. By default, MySQL looks for a tab character to separate the fields. However, if a tab doesn’t work for your data file, you can choose a different character to separate the fields and tell MySQL in the query that a different character than the tab separates the fields. Also by default, the end of a line is expected to be the end of a row — although you can choose a character to indicate the end of a line if you need to. A data file for the Pet table might look like this:

UnicornhorseSpiral horn5000.00/pix/unicorn.jpg
PegasushorseWinged8000.00/pix/pegasus.jpg
LioncatLarge; Mane on neck2000.00/pix/lion.jpg

A data file with tabs between the fields is a tab-delimited file. Another common format is a comma-delimited file, where commas separate the fields. If your data is in another file format, you need to convert it into a delimited file. To convert data in another file format into a delimited file, check the manual for that software or talk to your local expert who understands the data’s current format. Many programs, such as Excel, Access, and Oracle, allow you to output the data into a delimited file. For a text file, you might be able to convert it to delimited format by using the search-and-replace function of an editor or word processor. For a truly troublesome file, you might need to seek the help of an expert or a programmer.
The basic form of the LOAD query is

LOAD DATA INFILE “path/datafilename” INTO TABLE tablename

The query loads data from a text file located on your server. If the filename does not include a path, MySQL looks for the data file in the directory where your table definition file, called tablename.frm, is located. By default, this file is located in a directory named for your database, such as a directory named PetDirectory. This directory is located in your data directory, which is located in the main directory where MySQL is installed. For example, if the file was named data.dat, the LOAD command might look for the file at C:\Program Files\MySQL\MySQL Server 5.0\data\PetDirectory\ data.dat.
This basic form can be followed by optional phrases if you want to change a
default delimiter. The options are

FIELDS TERMINATED BY ‘character’
FIELDS ENCLOSED BY ‘character’
LINES TERMINATED BY ‘character’

Suppose that you have the data file for the Pet table, shown previously in this section, except that the fields are separated by a comma rather than a tab. The name of the data file is pets.dat, and it’s located in the same directory as the database. The SQL query to read the data into the table is

LOAD DATA INFILE “pets.dat” INTO TABLE Pet FIELDS TERMINATED BY ‘,’

To use the LOAD DATA INFILE query, the MySQL account must have the FILE privilege on the server host.

You can also load data from a text file on your local computer by using the word LOCAL, as follows:

LOAD DATA LOCAL INFILE “path/datafilename” INTO TABLE tablename

You must include a path to the file. Use forward slashes for the path, even on a Windows computer, such as “C:/data/datafile1.txt”. If you get an error message when sending this query, LOCAL may not be enabled.

To look at the data that you loaded — to make sure that it’s correct — use an SQL query that retrieves data from the database. I describe these types of SQL queries in detail in the next section. In brief, use the following query to look at all the data in the table so that you can check it:

SELECT * FROM Pet

How to add one row at a time to a database?

You use the INSERT query to add a row to a database. This query tells MySQL which table to add the row to and what the values are for the fields in the row.
The general form of the query is

INSERT INTO tablename (columnname, columnname,...,columnname)
VALUES (value, value,...,value)

The following rules apply to the INSERT query:
  • Values must be listed in the same order in which the column names are listed. The first value in the value list is inserted into the column that’s named first in the column list; the second value in the value list is inserted into the column that’s named second; and so on.
  • A partial column list is allowed. You don’t need to list all the columns. Columns that are not listed are given their default value or left blank if no default value is defined.
  • A column list is not required. If you’re entering values for all the columns, you don’t need to list the columns at all. If no columns are listed, MySQL will look for values for all the columns, in the order in which they appear in the table.
  • The column list and value list must be the same length. If the list of columns is longer or shorter than the list of values, you get an error message like this: Column count doesn’t match value count.
The following INSERT query adds a row to the Member table:

INSERT INTO Member (loginName,createDate,password,lastName, street,city,state,zip,email,phone,fax)
VALUES (“bigguy”,”2001-Dec-2”,”secret”,”Smith”, “1234 Happy St”,”Las Vegas”,”NV”,”88888”, “gsmith@GSmithCompany.com”,”(555) 555-5555”,””)


Notice that firstName is not listed in the column name list. No value is entered into the firstName field. If firstName were defined as NOT NULL, MySQL would not allow this. Also, if the definition for firstName included a default, the default value would be entered, but because it doesn’t, the field is left empty. Notice that the value stored for fax is an empty string. To look at the data that you entered and ensure that you entered it correctly, use an SQL query that retrieves data from the database. I describe these SQL queries in detail in “Retrieving information,” later in this chapter. In brief, the following query retrieves all the data in the Member table:

SELECT * FROM Member

Friday, April 4, 2008

How to add information?

Every database needs data. For example, you might want to add data to your database so that your users can look at it. Or you might want to create an empty database for users to put data into, making the data available for your eyes only — an example of this is the Member Directory. In either scenario, data will be added to the database.
If your data is still on paper, you can enter it directly into a MySQL database, one row at a time, by using an SQL query. However, if you have a lot of data, this process could be tedious and involve a lot of typing. Suppose that you have information on 1000 products that must be added to your database. Assuming that you’re greased lightening on a keyboard and can enter a row per minute, that’s 16 hours of rapid typing — well, rapid editing, anyway. Doable, but not fun. On the other hand, suppose that you need to enter 5000 members of an organization into a database and that it takes five minutes to enter each member. Now you’re looking at more than 400 hours of typing — who has time for that?
If you have a large amount of data to enter, consider some alternatives. Sometimes scanning in the data is an option. Or perhaps you need to beg, borrow, or hire some help. In many cases, it could be faster to enter the data into a big text file than to enter each row in a separate SQL query. The SQL query LOAD can read data from a big text file (or even a small text file). So, if your data is already in a computer file, you can work with that file; you don’t need to type all the data again. Even if the data is in a format other than a text file (for example, in an Excel, Access, or Oracle file), you can usually convert the file to a big text file, which can then be read into your MySQL database. If the data isn’t yet in a computer file and there’s a lot of data, it might be faster to enter that data into the computer in a big text file and transfer it into MySQL as a second step.
Most text files can be read into MySQL, but some formats are easier than others. If you’re planning to enter the data into a big text file, read the section, “Adding a bunch of data,” to find the best format. Of course, if the data is already on the computer, you have to work with the file as it is.

How to Move Data Into and Out of the Database?


An empty database is like an empty cookie jar — it’s not much fun. And searching an empty database is no more interesting or fruitful than searching an empty cookie jar. A database is only useful with respect to the information that it holds.
A database needs to be able to receive information for storage and to deliver information on request. For instance, the MemberDirectory database needs to be able to receive the member information, and it also needs to be able to deliver its stored information when you request it. If you want to know the address of a particular member, for example, the database needs to deliver that information when you request it.
Your MySQL database responds to four types of requests:
  • Adding information: Adding a row to a table.
  • Updating information: Changing information in an existing row. This includes adding data to a blank field in an existing row.
  • Retrieving information: Looking at the data. This request does not remove data from the database.
  • Removing information: Deleting data from the database.
Sometimes your question requires information from more than one table. For instance, the question, “How much does a green dragon cost?” requires information from the Pet table and from the Color table. You can ask this question easily in a single SELECT query by combining the tables. In the following sections, I discuss how to receive and deliver information as well as how to combine tables.

Wednesday, April 2, 2008

Changing the database structure

Your database isn’t written in stone. By using the ALTER query, you can change the name of the table; add, drop, or rename a column; or change the data type or other attributes of the column.
The basic format for this query is ALTER TABLE tablename, followed by the specified changes.
  • ADD columnname definition Adds a column; definition includes the data type and optional definitions.
  • ALTER columnname SET DEFAULT value Changes the default value for a column
  • ALTER columnname DROP DEFAULT Removes the default value for a column.
  • CHANGE columnname newcolumnname definition Changes the definition of a column and renames the colum, definition includes the data type and optional definitions
  • DROP columnname Deletes a column, including all the data in the column. The data cannot be recovered.
  • MODIFY columnname definition Changes the definition of a column; definition includes the data type and optional definitions.
  • RENAME newtablename Renames a table.
Changing a database is not a rare occurrence. You might want to change your database for many reasons. For example, suppose that you defined the column lastName with VARCHAR(20) in the Member table of the MemberDirectory database. At the time, 20 characters seemed sufficient for a last name. But now you just received a memo announcing the new CEO, John Schwartzheimer-Losertman. Oops. MySQL will truncate his name to the first 20 letters, a less-than-desirable new name for the boss. So you need to make the column wider — pronto. Send this query to change the column in a second:
ALTER TABLE Member MODIFY lastName VARCHAR(50)

Sunday, March 30, 2008

How to add tables to a database?

You can add tables to any database, whether it’s a new, empty database that you just created or an existing database that already has tables and data in it. You use the CREATE query to add tables to a database. Because a table is created in a database, you must indicate the database name where you want the table created. That is, when using the form , you must type a database name in the top field. If you don’t, you see the error message No Database Selected.
The query to add a table begins with

CREATE TABLE tablename

Next comes a list of column names with definitions. The information for each column is separated from the information for the next column by a comma. The entire list is enclosed in parentheses. Each column name is followed by its data type and any other definitions required. Here are some definitions that you can use:
  • NOT NULL: This column must have a value; it can’t be empty.
  • DEFAULT value: This value is stored in the column when the row is created if no other value is given for this column.
  • AUTO_INCREMENT: You use this definition to create a sequence number. As each row is added, the value of this column increases by one integer from the last row entered. You can override the auto number by assigning a specific value to the column.
  • UNSIGNED: You use this definition to indicate that the values for this numeric field will never be negative numbers.
The last item in a CREATE TABLE query indicates which column or combination of columns is the unique identifier for the row — the primary key.
Each row of a table must have a field or a combination of fields that is different for each row. No two rows can have the same primary key. If you attempt to add a row with the same primary key as a row already in the table, you get an error message, and the row is not added. The database design identifies the primary key. You specify the primary key by using the following format:

CREATE TABLE Member (
loginName VARCHAR(20) NOT NULL,
createDate DATE NOT NULL),
PRIMARY KEY(columnname) )

The columnname is enclosed in parentheses. If you’re using a combination of columns as the primary key, include all the column names, separated by commas. For instance, you would designate the primary key for the Login table in the MemberDirectory database by using this in the CREATE query:
PRIMARY KEY (loginName,loginTime)
Listing below shows the CREATE TABLE query used to create the Member table of the MemberDirectory database. You could enter this query on a single line if you wanted to. MySQL doesn’t care how many lines you use. However, the format shown in Listing below makes it easier to read. This human-friendly format also helps you spot typos.

CREATE TABLE Member (
loginName VARCHAR(20) NOT NULL,
createDate DATE NOT NULL,
password CHAR(255) NOT NULL,
lastName VARCHAR(50),
firstName VARCHAR(40),
street VARCHAR(50),
city VARCHAR(50),
state CHAR(2),
zip CHAR(10),
email VARCHAR(50),
phone CHAR(15),
fax CHAR(15),
PRIMARY KEY(loginName) )

Notice that the list of column names in Listing above is enclosed in parentheses (one on the first line and one on the last line), and a comma follows each column definition.
Remember not to use any MySQL reserved words for column names. If you do, MySQL gives you an error message that looks
like this:
You have an error in your SQL syntax near ‘order var(20))’ at line 1
Note that this message shows the column definition that it didn’t like and the line where it found the offending definition. However, the message doesn’t tell you much about what the problem is. The error in your SQL syntax that it refers to is the use of the MySQL reserved word order as a column name. After a table has been created, you can query to see it, review its structure, or remove it.
  • To see the tables that have been added to a database, use this query: SHOW TABLES
  • To see the structure of a table, use this query: DESCRIBE tablename
  • To remove any table, use this query: DROP TABLE tablename
Use DROP carefully because it is irreversible. After a table is dropped, it is gone forever. And any data that was in it is gone as well.

How to delete a database?

You can delete any database with this SQL query:
DROP DATABASE databasename
Use DROP carefully because it is irreversible. After a database is dropped, it is gone forever. And any data that was in it is gone as well.

How to create a new database?

To create a new, empty database, use the following SQL query:
CREATE DATABASE databasename where databasename is the name that you give the database. For instance, these two SQL queries create the sample databases used in this book:
CREATE DATABASE PetCatalog
CREATE DATABASE MemberDirectory
Some Web hosting companies don’t allow you to create a new database. You are given one database to use with MySQL, and you can create tables in only this one database. You can try requesting another database, but you need a good reason. MySQL and PHP don’t care that all your tables are in one database instead of organized into databases with meaningful names. It’s just easier for humans to keep track of projects when they’re organized.
To see for yourself that a database was in fact created, use this SQL query:
SHOW DATABASES
After you create an empty database, you can add tables to it.

Monday, March 24, 2008

A quick way to send SQL queries to the MySQL server

When MySQL is installed, a simple, text-based program called mysql (or sometimes the terminal monitor or the monitor) is also installed. Programs that communicate with servers are client software; because this program communicates with the MySQL server, it’s a client. When you enter SQL queries in this client, the response is returned to the client and displayed onscreen. The monitor program can send queries across a network; it doesn’t have to be running on the machine where the database is stored.
To send SQL queries to MySQL by using the mysql client, follow these steps:
  • Locate the mysql client. By default, the mysql client program is installed in the subdirectory bin, under the directory where MySQL is installed. In Unix/Linux, the default is /usr/local/mysql/bin or /usr/local/bin. In Windows, the default is c:\Program Files\MySQL\MySQL Server 5.0\bin. However, the client might be installed in a different directory. Or, if you’re not the MySQL administrator, you might not have access to the mysql client. If you don’t know where MySQL is installed or can’t run the client, ask the MySQL administrator to put the client somewhere where you can run it or to give you a copy that you can put on your own computer.
  • Start the client. In Unix and Linux, type the path/filename (for example, /usr/local/mysql/bin/ mysql). In Windows, open a command prompt window and then type the path\filename (for example, c:\ Program Files\MySQL\MySQL Server 5.0\bin\mysql). This command will start the client if you don’t need to use an account name or a password. If you need to enter an account or a password or both, use the following parameters:
    • u user: user is your MySQL account name.
    • p: This parameter prompts you for the password for your MySQL account.
For instance, if you’re in the directory where the mysql client is located, the command might look like this:

mysql -u root -p
  • If you’re starting the mysql client to access a database across the network, use the following parameter after the mysql command:
    • h host: host is the name of the machine where MySQL is located.
For instance, if you’re in the directory where the mysql client is located, the command might look like this:
mysql -h mysqlhost.mycompany.com -u root -p
Press Enter after typing the command.
  • Enter your password when prompted for it. The mysql client starts, and you see something similar to this: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 459 to server version: 5.0.15 Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer. mysql>
  • Select the database that you want to use. At the mysql prompt, type the following: use databasename Use the name of the database that you want to query.
  • At the mysql prompt, type your SQL query followed by a semicolon (;), and then press the Enter key. The mysql client continues to prompt for input and does not execute the query until you enter a semicolon. The response to the query is displayed onscreen.
  • To leave the mysql client, type quit at the prompt and then press the Enter key.
 
breast-cancer diabetes-informa... weight-losse lung-mesotheliom... eating-disorders medical-billing php-and-mysql skin-cancer medical-health astronomy-guide cancer-diseases health insurance seo-news-2008 forex3003 lawyer-lookingforalawyer earnmoneyonline-earn forexautotrading-forex forex-trade forextrading forex-trading-forex-trading-08 searchingforcancertreatment adsense jiankang8008 beauty-girl forex5005