What are the advantages of normalizing database structures in PHP applications?
Normalizing database structures in PHP applications helps reduce data redundancy, improve data integrity, and simplify data maintenance. By breaking down data into smaller, more manageable tables and establishing relationships between them, normalization ensures that data is stored efficiently and accurately.
// Example of normalizing a database structure in PHP using PDO
// Connect to the database
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
$pdo = new PDO($dsn, $username, $password);
// Create tables with normalized structures
$pdo->exec("CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(50)
)");
$pdo->exec("CREATE TABLE orders (
id INT PRIMARY KEY,
user_id INT,
total_amount DECIMAL(10,2),
FOREIGN KEY (user_id) REFERENCES users(id)
)");
// Insert data into the tables
$pdo->exec("INSERT INTO users (id, name, email) VALUES (1, 'John Doe', 'john@example.com')");
$pdo->exec("INSERT INTO orders (id, user_id, total_amount) VALUES (1, 1, 100.00)");
// Retrieve data with normalized structure
$stmt = $pdo->query("SELECT users.name, orders.total_amount FROM users
JOIN orders ON users.id = orders.user_id
WHERE users.id = 1");
while ($row = $stmt->fetch()) {
echo "Name: " . $row['name'] . ", Total Amount: $" . $row['total_amount'] . "\n";
}