How can a button in PHP trigger an SQL query to be sent to a database?

To trigger an SQL query to be sent to a database when a button is clicked in PHP, you can use a form with a button element that submits to a PHP script handling the database query. In the PHP script, you can check if the form has been submitted and then execute the SQL query based on the button click.

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

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

    // Execute SQL query based on button click
    $sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
    if ($conn->query($sql) === TRUE) {
        echo "Record inserted successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

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

<form method="post">
    <button type="submit" name="submit">Send SQL Query</button>
</form>