What best practices should be followed when handling form submissions and inserting data into a MySQL database using PHP?
When handling form submissions and inserting data into a MySQL database using PHP, it is important to sanitize and validate user input to prevent SQL injection attacks. Additionally, using prepared statements can help protect against SQL injection and improve performance. Finally, always remember to handle errors gracefully and provide feedback to the user.
// Connect to MySQL 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 and execute SQL statement
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
if ($stmt->execute()) {
echo "New record inserted successfully";
} else {
echo "Error: " . $conn->error;
}
// Close connection
$stmt->close();
$conn->close();
Related Questions
- What are some common issues when printing PDF files on dot matrix printers and how can PHP be used to address them?
- How can the CONCAT function in MySQL be utilized in PHP to combine two separate columns in a database query?
- How can error reporting and debugging be effectively utilized in PHP to troubleshoot issues like the one described in the thread?