What are the potential pitfalls of not normalizing a database when dealing with dynamic data exports in PHP?
When dealing with dynamic data exports in PHP, not normalizing the database can lead to redundant data, inconsistency, and potential data integrity issues. To solve this problem, it is important to normalize the database by breaking down data into separate tables and establishing relationships between them.
// Example of normalizing a database using PHP PDO
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Create tables for normalized data
$pdo->exec("CREATE TABLE users (
id INT PRIMARY KEY,
username 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 normalized tables
$pdo->exec("INSERT INTO users (id, username, email) VALUES (1, 'john_doe', 'john@example.com')");
$pdo->exec("INSERT INTO orders (id, user_id, total_amount) VALUES (1, 1, 100.00)");
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}