What are some common methods to integrate SQL queries with button clicks in PHP applications?

When integrating SQL queries with button clicks in PHP applications, one common method is to use AJAX to send the request to the server without reloading the page. This allows for a seamless user experience and prevents unnecessary page refreshes. Another method is to use PHP's built-in functions like mysqli or PDO to execute SQL queries when the button is clicked. This ensures that the data is securely processed on the server side.

// HTML button element with onclick event calling a JavaScript function
<button onclick="sendRequest()">Click me</button>

// JavaScript function using AJAX to send a POST request to a PHP file
<script>
function sendRequest() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        }
    };
    xhttp.open("POST", "process.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("data=someData");
}
</script>

// PHP file (process.php) receiving the AJAX request and executing SQL query
<?php
// Connect to database
$conn = new mysqli("localhost", "username", "password", "database");

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

// Retrieve data from AJAX request
$data = $_POST['data'];

// Execute SQL query
$sql = "INSERT INTO table_name (column_name) VALUES ('$data')";
if ($conn->query($sql) === TRUE) {
    echo "Record inserted successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

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