Jump to content

Recommended Posts

I am trying to use preg_match to validate input. I don't know why but when I push the submit button, instead of inserting the correct value, It inserts a 1.

 

I have a simple form that you type your name and push submit. When you do that, the code puts the name in a list above the form. There is a drop down menu that you can select the name from a list and push submit to delete the name. It all works. I tried to use preg_match to validate the name being input and I get a one every time I submit. I don't know why. This is all the code

 

$pattern = '/[A-Za-z]+/';
$name = preg_match($pattern, $_POST[name]);
if(isset($_POST[name]))
{
$sql="INSERT INTO mytable (names) VALUES ('$name')";
header("Location: http://localhost/php_sandbox/dbtest/index.php");
}

Link to comment
https://forums.phpfreaks.com/topic/178908-solved-help-with-form-validation/
Share on other sites

thats because preg_match returns true of false (or rather, values that evaluate to true of false)

you probably meant to do

$pattern = '/[A-Za-z]+/';
if (isset($_POST['name']) && preg_match($pattern, $_POST['name']))
           $name = $_POST['name'];
$sql="INSERT INTO mytable (names) VALUES ('$name')";
header("Location: http://localhost/php_sandbox/dbtest/index.php");
}

No they aren't optional. PHP will throw an 'Notice: Use of undefined constant ' if your not seeing it, then it's because of the way you have your error reporting set. Without the quotes PHP views it as a constant, when it realises the constant doesn't exists it will cast it to a string with the value of the name of the constant. Just because it fixes your mistakes though, doesn't mean you have to make them.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.