What are some best practices for handling database queries in PHP to ensure accurate results?
When handling database queries in PHP, it is crucial to use prepared statements to prevent SQL injection attacks and ensure data accuracy. Additionally, always sanitize user input to avoid any malicious code execution. Finally, test your queries thoroughly to guarantee they return accurate results.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare a SQL query with a placeholder for user input
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Sanitize user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
// Execute the query
$stmt->execute();
// Get the results
$result = $stmt->get_result();
// Loop through the results
while ($row = $result->fetch_assoc()) {
// Handle the data
}
// Close the statement and connection
$stmt->close();
$conn->close();