A database holds your most valuable asset, so access control isn't optional. This chapter covers creating users, granting only the privileges each one needs, and the single most important application-security rule: never build SQL by string concatenation.
Users & authentication
A MySQL user is name@host — the host limits where they can connect from:
CREATE USER 'app'@'10.0.0.%' IDENTIFIED BY 'a-strong-password';CREATE USER 'analyst'@'localhost' IDENTIFIED BY 'another-password';-- Never run the application as root; make a dedicated, limited user.
GRANT & least privilege
Grant the minimum privileges each user needs on the specific databases/tables — never blanket ALL on *.*:
-- The app needs to read/write its own database onlyGRANT SELECT, INSERT, UPDATE, DELETE ON albero.* TO 'app'@'10.0.0.%';-- The analyst needs read-onlyGRANT SELECT ON albero.* TO 'analyst'@'localhost';FLUSH PRIVILEGES;SHOW GRANTS FOR 'app'@'10.0.0.%';
Roles
From MySQL 8, a role bundles privileges you can grant to many users — change the role, change everyone at once:
CREATE ROLE 'read_only';GRANT SELECT ON albero.* TO 'read_only';GRANT 'read_only' TO 'analyst'@'localhost'; -- assign the role to a user
SQL injection — the cardinal sin
PREPARE stmt FROM 'SELECT * FROM students WHERE email = ?';SET @e = 'aanya@example.com';EXECUTE stmt USING @e; -- the value is data, never executed as SQLDEALLOCATE PREPARE stmt;
Practice
Create an app user with only CRUD on one database and an analyst with read-only, then verify with SHOW GRANTS. Bundle read-only into a role and assign it. Explain, in one sentence each, why running as root and why string-built SQL are dangerous.
Key takeaways
- 01A MySQL user is name@host; the host restricts where they can connect from.
- 02Grant least privilege on specific databases/tables — never ALL on *.* except for admins.
- 03Roles (MySQL 8+) bundle privileges so you manage many users through one grant.
- 04Never build SQL by concatenating input — use parameterised/prepared statements to stop injection.
- 05Run the app as a dedicated limited user, never as root.
