What are some best practices for handling database operations in PHP to ensure data integrity?
Issue: To ensure data integrity when handling database operations in PHP, it is important to use prepared statements to prevent SQL injection attacks, validate user input before executing queries, and handle errors gracefully to avoid data corruption. PHP Code Snippet:
// Establish 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 execute a SQL query using prepared statements
$stmt = $conn->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);
// Validate user input
$username = $_POST['username'];
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
} else {
// Execute the query
$stmt->execute();
echo "New record created successfully";
}
// Close statement and connection
$stmt->close();
$conn->close();
Related Questions
- What are the best practices for handling JavaScript functions in PHP for editing entries?
- How can one ensure that values from two arrays are combined in a new array, with a placeholder of 0 for missing values?
- What are the advantages of using the DateTime class in PHP for date calculations over traditional date functions?