Oops
Oops

Reputation: 1413

How to remove special characters to be get inserted into mysql database in php

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>'; 
}

Upvotes: 0

Views: 2249

Answers (1)

Ben Fried
Ben Fried

Reputation: 2204

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
}

Upvotes: 1

Related Questions