The Daily WTF
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
To read the full article click on the 'post' link at the top.