Basic if/else logic and security

I’ve put together the following:

[code]if(isset($_GET[‘addadmin’])){

echo "Employee Information

Last name: First name: ";

if(isset($_POST[‘submit2’])){
if(preg_match("/[A-Z | a-z]+/", $_POST[‘lastname2’])){
if(preg_match("/[A-Z | a-z]+/", $_POST[‘firstname2’])){
$firstname2=$_POST[‘firstname2’];
$lastname2=$_POST[‘lastname2’];

$db=mysql_connect (“localhost”, “test”, “pass”) or die (‘I cannot connect to the database because: ’ . mysql_error());
$mydb=mysql_select_db(“Training”);
$sql=“INSERT INTO staff (Last_Name, First_Name) VALUES ( '” . $lastname2 . "’, ‘" . $firstname2 . "’ )";
$result=mysql_query($sql);
echo "

Entry created for " . $lastname2 . ", " . $firstname2 . “

”;
}
}
else{
echo “

Please enter a valid name.

”;
}
}
}[/code]

Where I would like the form to require all information entered for variables ‘firstname2’ and ‘lastname2’ to conform to A-Z or a-z. It works, and even returns the else statement if one of the variables is incorrect.
However, if the user inputs a valid ‘lastname2’ value, but an invalid ‘firstname2’ value, the else statement does not run. I’m sure this is an oversight on my part, but I cannot figure out why it does not return “Please enter a valid name.” in this scenario. It at least prevents the submission from being INSERTed to the database. :slight_smile:

Question:
Could someone tell me why it doesn’t return the else statement when ‘lastname2’ is valid and ‘firstname2’ isn’t according to the preg_match?

[size=10pt]On a tangent[/size] size=8pt[/size]
This is my first project with PHP. How does one go about passing the MySQL database login to the server without the client having the opportunity to “View Source” it?

I have now come to notice the preg_match still allows users to include invalid characters in their entry.

So for example,
It disallows a ‘lastname2’ value of ‘123’, but will allow ‘Carlisle23’.

Is there a better/easier way to manage this?

I replaced the preg_match in the code above with:

if(preg_match("/^[A-Za-z]+$/", $_POST['name'])){

And it seems to have resolved the issue.

As for the security question, I replaced all instances of connecting to the db with

include 'opendb.php';

which points to a file that connects to the db, and it doesn’t seem to show up on the user end. I have not fully investigated this, but it is working for now.

I’ve since learned that a better way to parse dates and verify them is with the checkdate() function, but I really do not understand how it works well enough to use it. Could someone point me to a resource with more examples than the ones found on PHP’s website?

Sponsor our Newsletter | Privacy Policy | Terms of Service