How can HTML forms on a website be connected to a database using PHP scripts for data storage instead of just saving to a text file?

To connect HTML forms on a website to a database using PHP for data storage, you can use PHP to handle form submissions, validate the data, and then insert the data into the database. This involves establishing a connection to the database, preparing an SQL query to insert the form data, and executing the query to store the data in the database.

<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

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

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];

    // Prepare and execute SQL query to insert form data into database
    $sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

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