Let's say you have a database table containing a list of countries. Given the primary key of a country in that table- an arbitrary ID field- you need to look up the name of that country.

Curtis's predecessor dropped this solution:

function return_country($id) {
        $sql = "SELECT * FROM countries";
        $qry = db_query($sql);
                while($row = mysql_fetch_assoc($qry)){
                        $a[$row['id']] = $row['name'];
                return array();
        return $a[$id];

I guess they got the memo about not doing SQL injection flaws, but missed the "because you use query parameters". Instead, this queries the entire list of countries, iterates across them to build a mapping of ID to country name, and then uses that map to return the correct result.

This code really "shines" in its details. Sure, we could solve this with a query, but even if we opt to iterate across the table, we could just return from inside the loop. But no, we build an associative array.

And while it'd be better to return an error when the ID can't be found, we could return an empty string, but no- we return an empty array.

Return country? I'd rather return this code.

[Advertisement] ProGet’s got you covered with security and access controls on your NuGet feeds. Learn more.