What best practices should be followed when writing PHP code to interact with MySQL databases for form submissions?
When writing PHP code to interact with MySQL databases for form submissions, it is important to sanitize user input to prevent SQL injection attacks. Use prepared statements to prevent SQL injection and improve performance. Additionally, validate user input to ensure it meets the required format before inserting it into the database.
// Establish a connection to the 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 user input
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
// Prepare and execute the SQL statement
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
if ($stmt->execute()) {
echo "Record inserted successfully";
} else {
echo "Error: " . $conn->error;
}
// Close the connection
$stmt->close();
$conn->close();
Related Questions
- What are the advantages and disadvantages of using a CMS versus a microframework for developing a PHP website with SEO-friendly URLs?
- How can one extract specific information from a URL using PHP?
- What are the advantages and disadvantages of using manual entity escaping with functions like htmlspecialchars and htmlentities versus using a DOMDocument for HTML generation in PHP?