What are some common methods in PHP for storing data from a form in a database?
One common method in PHP for storing data from a form in a database is to use SQL queries to insert the form data into the database table. This involves connecting to the database, sanitizing the input data to prevent SQL injection attacks, and then executing an INSERT query to add the data to the database.
<?php
// Connect 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);
}
// Sanitize input data
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$message = mysqli_real_escape_string($conn, $_POST['message']);
// Insert data into database
$sql = "INSERT INTO form_data (name, email, message) VALUES ('$name', '$email', '$message')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Related Questions
- How can arrays be used to efficiently access the last element in a file in PHP?
- How can proper error handling techniques be implemented in PHP to prevent issues like class redeclaration errors?
- What are the advantages and disadvantages of using numeric versus associative indexes when fetching data from a MySQL query in PHP?