Article 6JF7M CodeSOD: Return Country

CodeSOD: Return Country

by
Remy Porter
from The Daily WTF on (#6JF7M)

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); if(mysql_num_rows($qry)>0){ while($row = mysql_fetch_assoc($qry)){ $a[$row['id']] = $row['name']; } }else{ 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.

proget-icon.png [Advertisement] ProGet's got you covered with security and access controls on your NuGet feeds. Learn more.
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments