How can PHP be used to write data to a database upon button click and handle redirection based on the outcome?

To write data to a database upon button click and handle redirection based on the outcome, you can use PHP to handle the form submission, insert the data into the database, and then redirect the user to a different page based on the success or failure of the database operation.

<?php
// Check if the form is submitted
if(isset($_POST['submit'])){
    // Connect to the database
    $conn = new mysqli('localhost', 'username', 'password', 'database');

    // Check the connection
    if($conn->connect_error){
        die("Connection failed: " . $conn->connect_error);
    }

    // Get the form data
    $data = $_POST['data'];

    // Insert data into the database
    $sql = "INSERT INTO table_name (column_name) VALUES ('$data')";
    if($conn->query($sql) === TRUE){
        // Redirect to success page
        header("Location: success.php");
        exit();
    } else {
        // Redirect to error page
        header("Location: error.php");
        exit();
    }

    // Close the connection
    $conn->close();
}
?>