string – How to remove special characters to be get inserted into mysql database in php-ThrowExceptions

Exception or error:

I have a textfield and if any special characters are attached to the string the value should not be inserted into the database. How can this be achieved in php? Thanks for the help in advance.

 if (preg_match('/[\'^£$%&*()"}{@#~?><>,|=_+¬-]/', $i)) {
  echo '<script language="javascript">'; 
  echo 'alert("Enter a valid Insurance Type.")'; echo '</script>'; 
How to solve:

If by “special” you mean non alpha-numeric, you could do something like this to strip out those characters before inserting them:

preg_replace("/[^a-zA-Z0-9\s\p{P}]/", "", $your_string);

Otherwise you could just check if the string is alpha-numeric, and only insert the record if it is:

if (ctype_alnum($your_string)) {
    // Do your MySQL insert

Leave a Reply

Your email address will not be published. Required fields are marked *