What are the best practices for handling database connections and queries in PHP to avoid deprecated functions or vulnerabilities like SQL injection?

To avoid deprecated functions and vulnerabilities like SQL injection in PHP, it is recommended to use PDO (PHP Data Objects) or MySQLi (MySQL Improved) for handling database connections and queries. These extensions provide prepared statements that help prevent SQL injection attacks and offer more secure and efficient ways to interact with databases.

// Using PDO for database connection and query
try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($result as $row) {
        // Handle each row
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}