Let's say you have an id and you want to lookup the corresponding name or other field from an sql table that relates to this unique id. Here's an example function in PHP that does it for you, but it might need to be tweaked a bit to fit the design of your sql-tables.
/* Get category name from a category id */ function getCategoryName($categoryId) { $select_category_query = sprintf("SELECT * FROM table_name WHERE id='%s'", $categoryId); $select_category_result = mysql_query($select_category_query);
if (!$select_category_result) { $message = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $select_category_query; die($message); } $row = mysql_fetch_row($select_category_result); return $row[1]; } |
The function above assumes that the sql-table has the following structure:
| Field names: | id | categoryName | Field2 | Field3 |
| Example row: | 34 | 'Some category' | 'donk' | 'blabla' |
The result row that comes from the php-command 'mysql_fetch_row' returns an array with the field values that corresponds to a row in the sql-table. The result row is also indexed as an array. This means that the first value is on index 0. So the value of field name 'id' is on position 0 in the resultset, i.e. $row[0], the value of field name 'categoryName' is on position 1 and so on. Hence, to get the category name in the example above with the specified sql table structure, field 'categoryName' is represented by $row[1] in the resultset.
When you have several tables in an application that relates to each other it is common to use values as id's instead of names. The reason for this is partly to save space but mainly to actually be able to change values only a one place without having to be forced to update large tables to replace strings.
So if you have a table where each row is a blog entry and one of the fields specifies the category of the blog entry you could choose to store this as the actual category string or an id which corresponds to a string in another table - a category table. If you ever need to change the name of a category you would need to update the entire blog entry table if you choose the string approach. If you would store it as an id you would only have to make the change in the category table.
The possible backside of this is possibly the extra database queries that has to be performed each time a blog entry is read to get the category name. Anyway, this is the place where you would need this function.