What are common errors that may occur when trying to save form data to a database using PHP?
Common errors that may occur when saving form data to a database using PHP include SQL injection vulnerabilities, improper data validation, and connection errors. To solve these issues, use prepared statements to prevent SQL injection, validate user input to ensure data integrity, and handle connection errors gracefully to provide feedback to the user.
// Establish a database connection
$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);
}
// Prepare and bind SQL statement to prevent SQL injection
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);
// Validate user input before saving to the database
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];
if ($stmt->execute()) {
echo "Data saved successfully";
} else {
echo "Error: " . $conn->error;
}
// Close connection
$stmt->close();
$conn->close();