What are best practices for handling database queries within PHP scripts, especially when using preg_match results?

When handling database queries within PHP scripts, especially when using preg_match results, it is important to sanitize user input to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries. This helps to separate the SQL query from the user input data, reducing the risk of malicious code execution.

// Assuming $db is your database connection object
$query = "SELECT * FROM users WHERE username = ?";
$stmt = $db->prepare($query);

if ($stmt) {
    $stmt->bind_param("s", $username);
    $username = $_POST['username']; // Assuming username is from user input
    $stmt->execute();
    
    // Handle query results here
} else {
    // Handle any errors with the prepared statement
}