04.27
I see this quite a lot, for example if you want to pull the value of the column `name` from a table using the ID:
$sql = “SELECT `name` FROM `tablename` WHERE `id`=’45′”;
$res = mysql_query ($sql);
$row = mysql_fetch_assoc ($res);
$name = $row['name'];
But if you use list () and mysql_fetch_array () you can trim it down somewhat…
$sql = “SELECT `name` FROM `tablename` WHERE `id`=’45′”;
$res = mysql_query ($sql);
list ($name) = mysql_fetch_array ($res);
Since mysql_fetch_array returns a numerically indexed list, and list () pulls the values of the resulting array to the specified variables, you don’t need to get the return and then extract the value from the array since you can do it all in one line.
In fact I generally abstract this whole block out to a function such as:
function sql_get_element ($table, $column, $value, $search=’id’)
{
$value = mysql_real_escape_string ($value);
$sql = “SELECT `$column` FROM `$table` WHERE `$search`=’$value’ LIMIT 1″;
$res = mysql_query ($sql);
list ($name) = mysql_fetch_array ($res);
return $name;
}
So if you wanted to fetch the name from a table with a specific ID you could do this:
$name = sql_get_element (‘tablename’, ‘name’, 45);
Thus cutting out a lot of the nonsense SQL calls, plus you centralise the data escaping to help ward off those troublesome SQL injection exploits.
No Comment.
Add Your Comment