How can PHP be used to connect a form to a MySQL database for data storage?

To connect a form to a MySQL database for data storage using PHP, you need to establish a connection to the database, retrieve the form data, sanitize and validate it, and then insert it into the database using SQL queries.

<?php
// Establish a connection to the MySQL database
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'your_database_name';

$conn = new mysqli($host, $username, $password, $database);

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

// Retrieve form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

// Sanitize and validate form data
$name = mysqli_real_escape_string($conn, $name);
$email = mysqli_real_escape_string($conn, $email);
$message = mysqli_real_escape_string($conn, $message);

// Insert form data into the database
$sql = "INSERT INTO your_table_name (name, email, message) VALUES ('$name', '$email', '$message')";

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

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