How can PHP developers ensure data integrity and consistency when linking articles to categories in a marketplace application?
To ensure data integrity and consistency when linking articles to categories in a marketplace application, PHP developers can implement foreign key constraints in their database schema. This will enforce referential integrity between the articles and categories tables, ensuring that only valid category IDs can be linked to articles.
// Add foreign key constraint to articles table
$sql = "ALTER TABLE articles
ADD CONSTRAINT fk_category_id
FOREIGN KEY (category_id)
REFERENCES categories(id)
ON DELETE CASCADE";
// Execute the SQL query
mysqli_query($conn, $sql);
Related Questions
- What is the function of mysql_insert_id in PHP and how does it handle multiple asynchronous requests?
- What are the potential pitfalls of using single quotes instead of double quotes for variables in SSH commands within PHP scripts?
- What are the best practices for structuring database queries using JOINs in PHP?