Now that you’ve seen how easy it is to use MySQL and created your first database, it’s time to look at how you create users, as you probably won’t want to grant your PHP scripts root access to MySQL—it could cause a real headache should you get hacked :).
To create a user, issue the GRANT command, which takes the following form (don’t type this in; it’s not an actual working command):
GRANT PRIVILEGES ON database.object TO ‘username’@’hostname’
IDENTIFIED BY ‘password’;
This should all look pretty straightforward, with the possible exception of the database.object part, which refers to the database itself and the objects it contains, such as tables.
- *.* All databases and all their objects
- database.* Only the database called database and all its objects
- database.object Only the database called database and its object called object
So, let’s create a new user who can access just the new tietokantadb database and all its objects, by entering the following (replacing the username asentaja and also the password passwordi with ones of your choosing):
GRANT ALL ON tietokantadb.* TO ‘asentaja’@’localhost’
IDENTIFIED BY ‘passwordi’;
What this does is allow the user asentaja@localhost full access to the tietokantadb database using the password passwordi. You can test whether this step has worked by entering
quit to exit and then rerunning MySQL the way you did before, but instead of entering ->
-u root -p, type -u asentaja -p, or whatever username you created.