How can PHP be used to maintain referential integrity and trigger stored procedures when handling contact data in a web application?

To maintain referential integrity and trigger stored procedures when handling contact data in a web application using PHP, you can utilize PHP's PDO (PHP Data Objects) extension to interact with a database. By setting up foreign key constraints in your database schema, you can enforce referential integrity. Additionally, you can call stored procedures using prepared statements in PHP to execute specific actions when inserting, updating, or deleting contact data.

<?php
// Connect to the database using PDO
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Set up foreign key constraints in the database
$pdo->exec("ALTER TABLE contacts ADD CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES users(id)");

// Define a stored procedure to be triggered when inserting contact data
$pdo->exec("CREATE PROCEDURE insert_contact(IN contact_name VARCHAR(255), IN user_id INT)
            BEGIN
                INSERT INTO contacts(name, user_id) VALUES(contact_name, user_id);
                -- Add any additional actions here
            END");

// Prepare and execute the stored procedure to insert contact data
$stmt = $pdo->prepare("CALL insert_contact(:contact_name, :user_id)");
$stmt->bindParam(':contact_name', $contact_name);
$stmt->bindParam(':user_id', $user_id);

$contact_name = 'John Doe';
$user_id = 1;

$stmt->execute();
?>