How can PHP be used to create a form that saves user input to a MySQL database?

To create a form that saves user input to a MySQL database using PHP, you need to first create an HTML form with input fields for the user to enter data. Then, use PHP to connect to the MySQL database, retrieve the form data using $_POST, sanitize the input to prevent SQL injection, and finally insert the data into the database using an SQL query.

<?php
// Connect to MySQL 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);
}

// Retrieve form data
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);

// Insert 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;
}

$conn->close();
?>