How can the normalization of database tables improve the efficiency and flexibility of storing and updating data compared to storing multiple values in a single string field in PHP?
Storing multiple values in a single string field in PHP can lead to data redundancy, inconsistency, and difficulty in querying and updating data. Normalizing database tables can improve efficiency and flexibility by organizing data into separate tables with relationships, reducing redundancy, ensuring data integrity, and allowing for easier querying and updating.
// Example of normalizing database tables in PHP
// Create a table for users
CREATE TABLE users (
id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL
);
// Create a table for user roles
CREATE TABLE user_roles (
id INT PRIMARY KEY,
user_id INT,
role VARCHAR(50) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id)
);
// Query to get user roles
SELECT users.username, user_roles.role
FROM users
JOIN user_roles ON users.id = user_roles.user_id;