Forum Moderators: coopster
I am working on a form submission process and would like to check if a user has entered a valid name. By valid, I mean the name contains upper and lowercase letters, hyphens, spaces and apostrophes. I'm using this to validate the name feild:
if (!preg_match("/^[a-zA-Z'- ]+$/",$fullName) ¦¦ strlen($fullName) < 3 ¦¦ strlen($fullName) > 32) {
$invalidName = 1;
header("Location: login.php?invalidName=1");
}
This works for names like Bob Smith, or Ahmed Al-Mahdi, but will not work for names such as John O'Connor. The apostrophe returns the invalidName error. Any suggestions?
Thanks,
Max
'John O'reilly'
Note that this is not a php error, it'sa mysql error. MySQL thinks your field value ended at "O' " and doesn't know what to do with the rest of it.
It's a matter of style. If you're always going to single-quote mysql values, simply double them up:
$field = preg_replace("/'+/","''",$field);
Which gives you this:
'John O''reilly'
Weird huh? But when it inserts it will insert properly:
John O'reilly
Same is true if you want to query:
$term = "John O'reilly";
$term = preg_replace("/'+/","''",$term);
$q = "select * from table where lname='$term';
Will work fine.