Let’s say you have a database table that contains 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.
CurtisThe predecessor rejected 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 the SQL injection flaws, but missed “because you’re using query parameters”. Instead, this examines the entire list of countries, iterates through 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. Of course, we could solve this with a query, but even if we choose to iterate over the table, we could just return
from inside the loop. But no, we are building an associative array.
And while it would be better to return an error when the ID cannot be found, we could return an empty string, but we don’t return an empty string.
Return country? I would rather return this code.
ProGet has you covered with security and access controls for your NuGet feeds. Find out more.