How can foreign key constraints be properly implemented in PHP when working with multiple database tables?
When working with multiple database tables in PHP, foreign key constraints can be properly implemented by defining the relationships between tables in the database schema and ensuring that any insert or update operations adhere to these constraints. This helps maintain data integrity and prevents orphaned records in the database.
// Define foreign key constraints in the database schema
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE orders (
id INT PRIMARY KEY,
user_id INT,
FOREIGN KEY (user_id) REFERENCES users(id)
);
// Ensure foreign key constraints are enforced in PHP code
$user_id = 1;
$query = "INSERT INTO orders (id, user_id) VALUES (1, $user_id)";
// Execute query and handle any errors