How can HTML forms on a website be connected to a database using PHP scripts for data storage instead of just saving to a text file?
To connect HTML forms on a website to a database using PHP for data storage, you can use PHP to handle form submissions, validate the data, and then insert the data into the database. This involves establishing a connection to the database, preparing an SQL query to insert the form data, and executing the query to store the data in the database.
<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
// Prepare and 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();
?>
Related Questions
- What best practices should be followed to prevent injection vulnerabilities when implementing user authentication and session management in PHP scripts?
- What are some best practices for handling SQL queries in PHP to avoid errors like the one mentioned in the forum thread?
- How can the issue of overwriting previous data in the database be resolved in PHP?