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 some best practices for managing sessions in PHP forms to ensure smooth functionality?
- How can the issue of cookies being overwritten on each request be avoided in PHP?
- What best practices can be implemented to handle long-running PHP scripts that may exceed the server's execution time limit?