You'll start working with the MySQL server using the client program mysql and a few simple database queries. Along the way, you'll play with some database settings, create some new users (without quite as much access to everything as the root user has), and get a taste of how queries work in practice.
Starting the mysql Client Program
Fire up the mysql client by issuing the following command at your command prompt:
Replace the USER, PASSWORD, and HOST arguments to reflect your personal settings. For example, if your database username and password are phpuser and phppass and you're connecting to the host db.whatever.com, the command would look like this:
All the arguments are optional. If missing, the following values are assumed for them:
The mysql client now connects to the database server running on the specified HOST with the given user ID/password combination. You may also specify a database to use by providing its name at the end of the command, like this:
You should see a response similar to the following:
If the mysql client complains that it can't connect to the specified server, check to see if the provided arguments are correct.
Selecting a Database to Use
To see the list of databases available, use the SHOW DATABASES command:
This is mostly the same information you got from mysqlshow earlier: there are still two databases, mysql and test, available in the system. This time, though, you're also told how many rows were returned (2) and how long it took the server to execute the query (0.00 seconds to two decimal places).
In fact, you can use the mysql client to do just about anything that the other, more specialized client programs can, as long as you know the correct syntax. Let's dig a little deeper.
To select a particular database, you can utilize the USE databasename syntax. Let's have a poke around inside one of the databases:
Your MySQL server is now ready to work with the database mysql. A word to the wise: be careful how you use the user table; it contains important information that you probably don't want to delete.
For the sake of readability, it is recommended that SQL keywords are written in uppercase characters, and user-defined names such as table and field names are lowercase. Remember that on the Linux/UNIX platforms, arguments are case-sensitive: Mysql, MYSQL, and mysql are all different database names.
Looking at Tables Inside a Database
You can use the SHOW TABLES command to list the existing tables in the currently selected database:
Once again, a slight elaboration on the results you previously got from mysqlshow. This time you can have a look at what's going on inside the tables. For example, let's see how the user table is structured. Use the DESCRIBE command, or DESC for short:
This command describes the user table's structure—what fields are defined and how they've been configured. For example, you can see the Host field can hold up to 60 characters and is defined as a primary key. The User field also is defined as a primary key. That doesn't mean that the Host and User fields are both primary keys (you should remember that this is forbidden). Instead, the combination of the Host and User fields works as a sole primary key in Host-User format.
For example, if user john at localhost has been given the server access privileges, localhost-john becomes the primary key value for his record. Another user at localhost whose name is also john cannot be inserted as a record in this table. However, john at whatever.com can.
All the fields in the user table except the Host, User, Password, are declared as ENUM('N', 'Y'). This means that only one from the specified set of values (either N or Y in this case) can be used in each field. Note that N is the default value when no value is provided.
Using SQL to Look at Data
All the queries you've given to the mysql client so far have been specific to the MySQL database engine, and won't necessarily work with another system, whether or not it supports SQL. Now that you're working down at the level of actual data, though, it's time to use some bona fide SQL statements to find out what's there.
Let's say you want to find out if there are any users registered with access privileges from the local machine localhost. You might do this by issuing the following SELECT query:
Because there are only three rows, it's not hard to see that only root is currently registered as a local user. Of course, it might be somewhat harder to spot this if you had a few hundred more users registered in the database, so here's another way to get the same result:
Using a WHERE clause narrows the scope of the retrieved records. This works much the same as PHP's if statement, except that the former uses a single equal sign (=) whereas the latter uses two (==) to test for equality.
If you wanted the server to retrieve all fields available instead of a few specified ones, you could use the * wildcard. For example:
This command would retrieve all of the records from tablename.
Manipulating Data in a Database
Now let's create a new database user, by inserting a new record into the user table using the INSERT command:
This INSERT query creates a record for the user phpuser, using the password phppass, in the user table, and specifies no access privileges. Each string value is placed within single quotes—this issue is discussed in greater detail later on. As you can see, the mysql client reports that the query was successfully executed, and that one row of data has been inserted as requested.
MySQL saves database user passwords after encrypting them. It uses its own password encryption scheme (which is different than Linux's), so use MySQL's built-in password() function to encrypt your password.
What if you change your mind and want to give user phpuser (who presently has no access privileges at all) the server administration privileges Reload_priv and Shutdown_priv? You could update the user table to reflect your whimsical decision using an UPDATE query, like this:
The mysql client reports that only one row matched the condition set in the query and that it has been successfully updated. User phpuser now has server administration privileges only: phpuser is only allowed to reload or shut down the server.
The WHERE clause is optional, and when omitted, the UPDATE query changes all the records in a given table with the new values provided. Warning: Make sure you don't change records by accident. A nightmare can sometimes turn into reality if you're not careful because a careless UPDATE query could, for example, change 10,000 user records to have the same password. Even worse, all the records in a table could unwittingly be deleted with a DELETE query such as:
Here all of the records in the table test have been deleted. Don't be fooled by the mysql client reporting that no row is affected by this query. Following the query, the server has no way of knowing how many rows are affected (deleted) because they're gone forever after the query. Note that the syntax of this example DELETE command contains no clauses. Thankfully, you may specify which records are to be deleted with a WHERE clause:
Now you change you mind again and want to give user phpuser all of the server administration privileges. What do you do? You can make either another UPDATE query or you can REPLACE the whole record. The syntax is pretty simple:
So REPLACE overwrites an old record with a new one. Note that the new record and the old record must have the same value in a field designated as a key (or the combined key formed by the Host and User fields in this case). The difference between the UPDATE and REPLACE commands is that UPDATE replaces only the selected set of fields in a record, whereas REPLACE replaces the whole record with the given values.
Finally, to activate the newly created account phpuser, you need to flush privileges, reloading the privilege information from the table. (The server normally reads the access privilege information only once, when it's loaded.) First, exit mysql client, by typing quit, (otherwise you'll get an error saying that your SQL syntax is incorrect). Then:
Alternately you can issue the FLUSH PRIVILEGES command to reflect the change in the mysql client program:
Using GRANT and REVOKE Commands
GRANT and REVOKE commands enable you to allocate and remove database privileges as you choose. They can be used at various levels of your database permissions structure, going from global to database to table to column level—depending on how fine grain you want your control to be. Of course, for whatever permissions you can grant a user, you can use a corresponding REVOKE statement to remove them.
In the following sections you'll see how to use these commands to control permissions on your tables. For example, earlier you created a new user by manipulating the user table directly. You can achieve the same goal more simply using the GRANT command. Let's see how.
GRANT
Here's the simplest form of the GRANT command:
It gives every access privilege on every database in the system to the user phpuser at localhost if he logs on to the server using the password phppass. Note that the user and host arguments are not given in quotes.
If you want to let this user access the tables in the test database only, you'd use the following command:
Here, test.* denotes all tables in the test database. Similarly you can grant access to only the sample table in test:
By replacing the ALL PRIVILEGES keyword with a selection of query types, a set of access privileges can be granted:
With this command, the user phpuser can issue only SELECT, INSERT, and UPDATE queries to any of the tables in the test database. Any other query, such as DELETE, won't be allowed. Wildcards like * are extremely useful. For example, by replacing localhost with the % wild card, you can allow the user phpuser to access the specified tables from any server.
You can also specify the host with a partial domain name: if you used phpuser@%.whatever.com for instance, only users with the user ID phpuser connecting from the domain whatever.com would be granted access to the server.
You can split hairs even further, by specifying the fields that the user can access:
Here the user phpuser can issue only SELECT queries on the User and Host fields in the user table.
You can use the WITH GRANT OPTION clause to give the specified user the capability to grant other users any privileges he has at the specified privilege level:
This command is equivalent to creating another superuser, called phpuser. Be careful with the WITH GRANT OPTION clause: two users with different privileges can easily team up and extend their privileges by exchanging them!
REVOKE
The REVOKE command removes access privileges from a user. If you want to revoke all privileges given to user phpuser, for example, issue the following command:
You can specify multiple usernames by separating them with commas:
All specified users must exist, and possess the specified privileges, in order for this command to work.
The following command revokes only the SELECT privilege from the user phpuser:
Again, you can split hairs by specifying field names:
If you modify the grant tables using GRANT or REVOKE commands, the changes take effect immediately. You don't have to flush privileges or reload the server.