// Connect to database $dsn = 'mysql:host=localhost;dbname=mydatabase'; $username = 'myusername'; $password = 'mypassword'; $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); try { $db = new PDO($dsn, $username, $password, $options); } catch(PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } // Save message to database $sender = 'John'; $recipient = 'Jane'; $message = 'Hello, how are you?'; $date = date('Y-m-d H:i:s'); $sql = "INSERT INTO messages (sender, recipient, message, date) VALUES (:sender, :recipient, :message, :date)"; $stmt = $db->prepare($sql); $stmt->bindParam(':sender', $sender); $stmt->bindParam(':recipient', $recipient); $stmt->bindParam(':message', $message); $stmt->bindParam(':date', $date); $stmt->execute(); // Retrieve messages from database $sql = "SELECT * FROM messages WHERE sender = :sender"; $stmt = $db->prepare($sql); $stmt->bindParam(':sender', $sender); $stmt->execute(); $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach($messages as $row) { echo $row['recipient'] . ': ' . $row['message'] . ' (' . $row['date'] . ')' . 'In this example, we are saving a message to a MySQL database with the sender, recipient, message content, and date. We then retrieve messages from the database based on the sender and display them. The package library used in this example is PDO, which is a PHP extension for interacting with databases.
'; }