How can form data be processed and used in PHP to interact with a MySQL database?
To process form data in PHP and interact with a MySQL database, you can use the $_POST superglobal to retrieve the form data submitted by the user. You can then establish a connection to the MySQL database using mysqli or PDO, sanitize the input data to prevent SQL injection attacks, and execute SQL queries to insert, update, or retrieve data from the database.
<?php
// Retrieve form data using $_POST superglobal
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Establish a connection 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);
}
// Sanitize input data
$name = mysqli_real_escape_string($conn, $name);
$email = mysqli_real_escape_string($conn, $email);
$message = mysqli_real_escape_string($conn, $message);
// Execute SQL query to insert data into database
$sql = "INSERT INTO messages (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 database connection
$conn->close();
?>
Keywords
Related Questions
- How can including URLs in PHP comment lines potentially compromise the security of a website?
- What are some common pitfalls to avoid when implementing streaming functionality on a PHP server for a custom player?
- What are some best practices for handling directory entries when using the ftp_nlist function in PHP?