RetroCode UK

Published Date Jun 20, 2011 Reading Time ~1 minutes RSS Feed Software Development

Sample Class to Escape a MySQL Input Value

IMPORTANT: This content is over 1 year old, and may now be obsolete, irrelevant and/or no longer accurate.

There was quite a simple but effective snippet I came across recently that highlights how PHP getters (magic methods) can be useful.

Please don’t use this code as it is, as it’s for illustrative purposes only; it doesn’t check for magic quotes that the server may be using, and you may want to do additional purification of the data according to the field’s content. However, I do think it’s a useful example of how classes can be used effectively, and this could be expanded, in theory, to add a static type for input type, that’s initialised during __construct(), which could make it a little more dynamic.

class dbQuoteStr
    function __get($value)
        return mysql_real_escape_string($value);
$dbQuoteStr = new dbQuoteStr();

To use the above class, all you need to do is:

mysql_query("SELECT * FROM users WHERE name LIKE
'{$dbQuoteStr->$name}' LIMIT 10");