How can PHP be used to dynamically insert user-inputted data into specific database columns based on button clicks?

To dynamically insert user-inputted data into specific database columns based on button clicks, you can use PHP to handle the form submission and insert the data into the database accordingly. You can use JavaScript to capture the button clicks and send the necessary information to the PHP script for processing.

<?php
// Assuming you have a form with input fields and buttons
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Connect to your database
    $conn = new mysqli("localhost", "username", "password", "database");

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

    // Retrieve user input from the form
    $data1 = $_POST['data1'];
    $data2 = $_POST['data2'];

    // Check which button was clicked
    if (isset($_POST['button1'])) {
        $sql = "INSERT INTO your_table (column1) VALUES ('$data1')";
    } elseif (isset($_POST['button2'])) {
        $sql = "INSERT INTO your_table (column2) VALUES ('$data2')";
    }

    // Execute the SQL query
    if ($conn->query($sql) === TRUE) {
        echo "Data inserted successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

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