0

I'm new to php and mysql and I'm trying to check if a user has entered something into a a coupls of textboxes and to also check if what has been entered is string. I want to do a check before posting to the database. I also want the html form to retain the value initially entered by the user. Please how do i achieve this.

Here's what I've done so far. This works but it still shows that the data has been entered successfully.

if(isset($_POST['register'])){  
//PHP FIELD VALIDATIONS
if($_POST['fname']==""){
    echo "First name is required <br/>";

}
else{
   $fname= filter_var($_POST['fname'], FILTER_SANITIZE_STRING);
}
if($_POST['lname']==""){
    echo "Last name is required <br/>";
}
else{
    $lname= $_POST['lname'];
}
if($_POST['email']==""){
    echo "Email address is required <br/>";
}
else{
     $email= $_POST['email'];
}
if($_POST['pword']==""){
    echo "Password is required<br/>";
}
else{
      $pword= $_POST['pword'];
}  

$fname=mysql_real_escape_string($fname);
$lname=mysql_real_escape_string($lname);
$email=mysql_real_escape_string($email);
$pword=mysql_real_escape_string($pword);

require_once 'scripts/connect_to_mysql.php';
$sql = "INSERT INTO customer ".
       "(First_name,Last_name, Email, Password, date_added) ".
       "VALUES('$fname','$lname','$email','$pword', NOW())";
       //echo $sql;
mysql_select_db('online_store');
$result = mysql_query( $sql, $conn );
if(! $result )

{
  die('Could not enter data: ' . mysql_error());
}
echo "<span style='color:green;'>Entered data successfully</span>";
mysql_close($conn);
}
?>
seun
  • 27
  • 1
  • 5
  • 11

3 Answers3

0

Form Validation:

You'll need a mechanism that validates fields in your form and echos some validation error. The way you write php is pretty outdated, today php application usually use a pattern like MVC for the separation of concerns. Read about both, MVC and SoC.

However, the most simple solution here would be a validation class:

class Validator {
    public static function email($postField, $message) {
        if (isset($_POST[$postField]) {
            // Example of full email validation here https://github.com/cakephp/cakephp/blob/master/lib/Cake/Utility/Validation.php#L437
            $regex = '...'; 

            if (!preg_match($regex, $email)) {
                return $message;
            }
        }
    }
    public static function notEmpty($postField, $message) {
         if (isset($_POST[$postField]) && empty($_POST[$postField])) {
             return $message;
         }
    }
    public static function multi($field, $rules = array()) {
        foreach ($rules as $rule => $message) {
            echo Validator::{$rule}($field, $message);
        }
    }
}

echo Validator::email('email', 'Your email address is wrong!');
Validator::multi('email', array('email' => '...', 'notEmpty' => '...'));

This is a very basic example but you get the idea. This could be extended and improved a lot to automate it much more.

Honestly I'm not in the mood to write a complete article about that right now because I guess there are plenty of them already, just try to Google for server side form validation in the context of php.

Database:

You're using the as deprecated flagged mysql_* functions, don't use them, use mysqli or PDO instead.

There is a big warning for these functions on each documentation page:

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.

For how you properly use and escape SQL queries see this: How can I prevent SQL injection in PHP?

PDO example.

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
    // do something with $row
}
Community
  • 1
  • 1
floriank
  • 25,546
  • 9
  • 42
  • 66
  • Thanks for the suggestions @burzum, however, how does that solve the above problem? – seun Apr 09 '14 at 10:31
0

Firstly and most importantly, you should change from mysql to either mysqli or PDO.

Secondly, to ensure all fields are entered before submitting, you could loop through the inputs, checking each if they are empty, and running any input specific checks you wish. i.e checking if an input is a string you can do is_string($variable).

If any of the checks fail, set a variable e.g. $failedValidation, then wrap your sql execution code in an if statement - if $failedValidation !isset, or is set to false, however you want to handle it - then run the code.

Instead of using $fname=mysql_real_escape_string($fname); use $fname = htmlspecialchars($fname);.

Looping through $_POST array:

$Validated = True; // Validated needs to be set to true, for the SQL code to run

// Loop through all variables stored in the $_POST array
foreach($_POST as $value) 
{
    if(empty($value))  // If any of the $_POST variables are empty, set $Validated to false
    {
       $Validated = False;
    }
}

// If none of the fields were empty, $Validated will have remained true after our loop
if($Validated == True) {
   // Run SQL code
}

Hopefully I've explained it in a way you can understand, and I hope it helps you.

d.abyss
  • 204
  • 1
  • 4
  • 26
  • Thanks @danielsmile I'd keep your suggestions in mind. Could u show an example of how to loop please? Plus can is it advisable to use php's filter_var() to validate user input? Please reply. – seun Apr 09 '14 at 15:35
  • @seun filter var is used mostly for validating email, an example of it's usage is `(filter_var($email, FILTER_VALIDATE_EMAIL)`. This is server side validation. If you wish to heavily validate you can use client side validation techniques too - see this link for example http://www.w3schools.com/tags/att_input_required.asp – d.abyss Apr 09 '14 at 15:59
  • @seun As for looping through input fields for validation - remember that $_POST is an array, you can loop through it just as you would a normal array. I'll edit my post to show you a simple example of usage. – d.abyss Apr 09 '14 at 16:06
-2

Use below code:

if(isset($_POST['register'])){  
    //PHP FIELD VALIDATIONS
    $validated = true;
    if($_POST['fname']==""){
        echo "First name is required <br/>";
        $validated = false;
    }
    else{
       $fname= filter_var($_POST['fname'], FILTER_SANITIZE_STRING);
    }
    if($_POST['lname']==""){
        echo "Last name is required <br/>";
        $validated = false;
    }
    else{
        $lname= $_POST['lname'];
    }
    if($_POST['email']==""){
        echo "Email address is required <br/>";
        $validated = false;
    }
    else{
         $email= $_POST['email'];
    }
    if($_POST['pword']==""){
        echo "Password is required<br/>";
        $validated = false;
    }
    else{
          $pword= $_POST['pword'];
    }  
    if ($validated) {
        $fname=mysql_real_escape_string($fname);
        $lname=mysql_real_escape_string($lname);
        $email=mysql_real_escape_string($email);
        $pword=mysql_real_escape_string($pword);

        require_once 'scripts/connect_to_mysql.php';
        $sql = "INSERT INTO customer ".
               "(First_name,Last_name, Email, Password, date_added) ".
               "VALUES('$fname','$lname','$email','$pword', NOW())";
               //echo $sql;
        mysql_select_db('online_store');
        $result = mysql_query( $sql, $conn );
        if(! $result )

        {
          die('Could not enter data: ' . mysql_error());
        }
        echo "<span style='color:green;'>Entered data successfully</span>";
        mysql_close($conn);
    }
}
Elixir Techne
  • 1,848
  • 15
  • 20
  • 1
    Downvoted because: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. – floriank Apr 09 '14 at 10:29
  • @burzum, the question was about incorrect behavior in PHP, it not fair to downvote for MySQLi. – Elixir Techne Apr 09 '14 at 10:45
  • Well, that's no reason to not mention and to not correct outdated / bad practice? Nor your answer contains any kind of explanation of how and why you did something. It's basically "eat this and die". There is zero learning benefit from this answer. Plus you repeat the same check over and over (considered as bad practice, it's not DRY). – floriank Apr 09 '14 at 10:46