What are the best practices for integrating PHP with HTML forms and databases for data storage?
When integrating PHP with HTML forms and databases for data storage, it is important to properly sanitize user input to prevent SQL injection attacks. Additionally, using prepared statements when interacting with the database can help prevent against SQL injection vulnerabilities. Lastly, validating user input on the server-side before processing and storing it in the database is crucial for data integrity.
<?php
// 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);
}
// Sanitize user input
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['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 created successfully";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
$conn->close();
?>
Keywords
Related Questions
- What alternative methods can be used to access cookie information if it is not immediately readable in PHP?
- Does a session in PHP automatically have a name, or is it necessary to assign one?
- How can one efficiently store and access multi-dimensional arrays in PHP when dealing with parent-child relationships in database query results?