How can PHP be used to process form data and interact with a database effectively?
To process form data and interact with a database effectively using PHP, you can use the $_POST superglobal to retrieve form data submitted by the user. Then, you can establish a connection to the database using mysqli or PDO, execute SQL queries to insert or retrieve data, and handle any errors that may occur during the process.
// Retrieve form data using $_POST superglobal
$name = $_POST['name'];
$email = $_POST['email'];
// Establish a connection to the 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);
}
// Execute SQL query to insert form 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;
}
// Close database connection
$conn->close();