How can PHP be used to handle form data submission and insertion into a MySQL database?
To handle form data submission and insertion into a MySQL database using PHP, you can create a PHP script that retrieves the form data using $_POST or $_GET superglobals, connects to the MySQL database using mysqli or PDO, and then inserts the data into the database table using SQL queries.
<?php
// Retrieve form data
$name = $_POST['name'];
$email = $_POST['email'];
// 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 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();
?>
Related questions
-
deprecated PHP functions mysql_connect
-
bindParam table names SQL queries
-
date functions array manipulation file handling