Skip to content

Instantly share code, notes, and snippets.

@abdullahbutt
Created November 10, 2013 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdullahbutt/7403362 to your computer and use it in GitHub Desktop.
Save abdullahbutt/7403362 to your computer and use it in GitHub Desktop.
CI function form prep
Save Database Crashes: 'prep' Your Data Entry Forms
Data entry is fraught with problems. Because of limitations of HTML and databases, data that contain certain symbols— for example, apostrophes and quotation marks—may cause your database to crash or to give results you did not expect.
The answer to this is to prepare or 'prep' your data in your data entry form, before it is submitted to the database. All this takes time and a certain amount of extra coding.
CI's form helper does this, automatically. So, when you create an input box by typing:
echo form_input('username', 'johndoe');
You're also getting the hidden benefit of:
function form_prep($str = '')
{
if ($str === '')
{
return '';
}
$temp = '__TEMP_AMPERSANDS__';
// Replace entities to temporary markers so that
// htmlspecialchars won't mess them up
$str = preg_replace("/&#(\d+);/", "$temp\\1;", $str);
$str = preg_replace("/&(\w+);/", "$temp\\1;", $str);
$str = htmlspecialchars($str);
// In case htmlspecialchars misses these.
$str = str_replace(array("'", '"'), array("'",
"""), $str);
// Decode the temp markers back to entities
$str = preg_replace("/$temp(\d+);/","&#\\1;",$str);
$str = preg_replace("/$temp(\w+);/","&\\1;",$str);
return $str;
}
This is code that handles special characters like '&'; so that they don't cause confusion while your form is being submitted. As you can see, there is some quite tricky regex code in there.
Possibly you like typing out regexes. Some people like lying on beds of nails, some like listening to ABBA; it's a free country. (Well, it is where I'm writing this.) But if you don't like these things, you can let CI do them for you (the regexes, I mean, not ABBA), and you needn't even be aware of the code that's working away in the background for you, every time you write that one simple line of code:
echo form_input('username', 'johndoe');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment