What is the difference between a Primary Key and a Foreign Key in the context of PHP and MySQL databases?
Primary Key is a unique identifier for each record in a table, used to uniquely identify each row in the table. Foreign Key is a field in a table that is a primary key in another table, used to establish a relationship between the two tables.
// Creating a table with a Primary Key
$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL
)";
// Creating a table with a Foreign Key
$sql = "CREATE TABLE orders (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id INT(6) UNSIGNED,
total_amount DECIMAL(10,2),
FOREIGN KEY (user_id) REFERENCES users(id)
)";
Keywords
Related Questions
- What are best practices for handling variable-length sentences with colored words in fpdf output?
- How can PHP be used to create batch files for specific tasks, such as shutting down or restarting a Windows PC?
- What are some common methods for handling time calculations in PHP, and what are the potential pitfalls associated with each method?