In PHP, what are the benefits of normalizing tables and reducing data duplication in database queries?

Normalizing tables and reducing data duplication in database queries can improve database performance, reduce storage space, and maintain data integrity by minimizing redundant data. By breaking down data into smaller, related tables and using relationships like foreign keys, you can avoid storing the same information multiple times. This also makes it easier to update data consistently and avoid inconsistencies.

// Example of normalizing tables in PHP using MySQLi

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Create a table for users
$mysqli->query("CREATE TABLE users (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(30) NOT NULL,
    email VARCHAR(50) NOT NULL
)");

// Create a table for user addresses
$mysqli->query("CREATE TABLE addresses (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id INT(6) UNSIGNED,
    address VARCHAR(100) NOT NULL,
    FOREIGN KEY (user_id) REFERENCES users(id)
)");

// Insert data into the tables
$mysqli->query("INSERT INTO users (username, email) VALUES ('JohnDoe', 'johndoe@example.com')");
$user_id = $mysqli->insert_id;
$mysqli->query("INSERT INTO addresses (user_id, address) VALUES ($user_id, '123 Main St')");