What are some best practices for handling foreign keys in MySQL tables when using PHP?

When handling foreign keys in MySQL tables with PHP, it is important to ensure that the foreign key constraints are properly defined in the database schema. This helps maintain data integrity by enforcing referential integrity between related tables. Additionally, when performing operations that involve foreign keys, such as inserting or updating data, it is crucial to handle any potential errors that may arise due to constraint violations.

// Example of defining foreign key constraints in MySQL table
$createTableQuery = "CREATE TABLE orders (
    id INT PRIMARY KEY,
    customer_id INT,
    FOREIGN KEY (customer_id) REFERENCES customers(id)
)";

// Example of inserting data into a table with foreign key constraint
$insertQuery = "INSERT INTO orders (id, customer_id) VALUES (1, 123)";
try {
    $result = $pdo->exec($insertQuery);
    if ($result === false) {
        throw new Exception("Error inserting data into orders table");
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}