How can JavaScript variables be passed to PHP for storage in a database?

To pass JavaScript variables to PHP for storage in a database, you can use AJAX to send the data from the client-side JavaScript to a PHP script on the server. The PHP script can then process the data and store it in the database using SQL queries. This allows for seamless communication between the client-side and server-side code.

<?php
if(isset($_POST['variable_name'])){
    $variable_value = $_POST['variable_name'];
    
    // Connect to database
    $conn = new mysqli('localhost', 'username', 'password', 'database_name');
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    // Insert variable into database
    $sql = "INSERT INTO table_name (column_name) VALUES ('$variable_value')";
    
    if ($conn->query($sql) === TRUE) {
        echo "Variable stored successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    
    $conn->close();
}
?>