What are the best practices for saving form data in a database using PHP?
When saving form data in a database using PHP, it is important to sanitize the input to prevent SQL injection attacks. It is also crucial to validate the data to ensure it meets the required format before saving it to the database. Additionally, using prepared statements can help prevent SQL injection and improve performance.
<?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 and validate form data
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
// Prepare SQL statement
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
// Execute the statement
$stmt->execute();
// Close the statement and connection
$stmt->close();
$conn->close();
?>
Related Questions
- What is the significance of using UTF-8 consistently in PHP applications, especially when dealing with database connections?
- How can the use of var_dump() in PHP help troubleshoot issues related to SQL query construction and execution?
- What is the difference between using fopen and cURL for handling redirects in PHP?