Added on: Tuesday 24th November 2009
Normally you wouldn't do this because you will have defined the field as numeric when setting up the table.
However, if you want to create an application with as much flexibility as possible there will be times when you might need this.
I often use it in our CMS because it allows 'user defined fields' in any record type.
The data is stored in an additional table which references the correct record and field.
As all the data for any user defined field is stored in the same table it has to be stored as text in order to allow the maximum number of 'types' of data.
Any validation is done on the input form so effectively you can have different data types.
So an example might be that a 'Price' field is added to the standard content record for listing products (the full e-commerce module has a separate table for products but a small site wouldn't have this) and this would need to be sorted in ascending or descending order.
If for example you had several entries such as 5.00, 10.99, 1.45 and 6.35 then the SQL statement:
SELECT user_value FROM table ORDER BY user_value
would return 1.45, 10.99, 5.00 and 6.35.
There are several ways you can sort this (excuse the pun!).
SELECT user_value FROM table ORDER BY (user_value+0)
SELECT user_value FROM table ORDER BY CAST(user_value, INT)
and
SELECT user_value FROM table ORDER BY LPAD(user_value,10,'0')
All of the above work and I don't think it really matters which is used. I would guess that the overhead is slightly greater for the last two (although an internal conversion probably has to be done for the first one) but I haven't tested them against each other.
Be careful with the last one which in the example above pads each record with zeros until the result is 10 characters long - if the original value is more than ten characters it will get truncated.
Andrew Parrott runs Round Ash Associates, a web design and development company based in Chagford on Dartmoor, Devon.
If you prefer updates via email then please enter your email address below and click Submit.
If you haven't been to Chagford before then take a look a what you are missing.
Sitepoint is an indespensible resource for web designers.
Internet Explorer isn't the only web browser and from a development point of view Firefox is much better.
As many of the articles on this site are slightly techy I thought I ought to link to a glossary of Internet terms.
The layout for this site uses one of Matthew James Taylors 'liquid layouts'.
©Round Ash Associates 2009. Powered by form2list.