How can PHP variables be effectively used to fill entries in MySQL tables when submitting a form?

When submitting a form, PHP variables can be used to capture the form data and then insert this data into MySQL tables. To achieve this, you can use the $_POST superglobal array to retrieve the form data, assign it to PHP variables, and then use these variables in an SQL query to insert the data into the MySQL table.

<?php
// Retrieve form data using $_POST superglobal
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Insert form data into MySQL table
$sql = "INSERT INTO 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;
}

$conn->close();
?>