How can PHP be integrated with HTML forms to effectively handle user registration on a website?
To effectively handle user registration on a website using PHP and HTML forms, you can create a registration form in HTML with input fields for the user to enter their information. Then, use PHP to process the form data, validate it, and insert it into a database. This involves setting up a connection to the database, sanitizing user input to prevent SQL injection attacks, and displaying appropriate error messages if any validation fails.
<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Connect to the database
$conn = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sanitize user input
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
// Insert user data into the database
$sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
if ($conn->query($sql) === TRUE) {
echo "User registered successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>