Jump to content

Recommended Posts

Hi

I'm have a PHP form that submits to a MYSQL database and I'm trying to make it so when any form input field is empty the user gets a message below that field and the data isn't submitted. I can't seem to get it work though?

The data submits OK when I don't have any validation but obviously if the fields are empty then a blank record just gets added to the database.

 

    <?php 
      
        // submit data to database
        if (isset($_POST['submit'])) {

            // assign variable names to name attributes from the form
            $firstname = $_POST['first-name'];
            $email = $_POST['email'];
			
			// This is the attempted validation code
            if(empty($firstname)) {
                $error= "<br>- Please enter your firstname";
            }
            if(empty($email)) {
                $error="<br>- Please enter your email";
            }

            if ($error) {
                $result="<p class='alert error'>There is an error. Please correct the following: {$error}</p>";
            } else {
		
            // This is when the data is submitted
            $query = "INSERT INTO users(firstname, email) VALUES(?,?)";

            $stmt = $connection->prepare($query);
            $stmt->bind_param("ss", $f, $e);

            $f = $firstname;
            $e = $email;
            $stmt->execute();

            $stmt->close();
            $connection->close();

            header("Location: index.php"); // makes page refresh after query so new records show in HTML table

        }
        
    }
    ?>

 

6 minutes ago, gw1500se said:

That is not something that should be done on the server side (PHP). It should be done on the client side (Javascript).

Surely someone can just go into the dev tools and turn this validation off if it's in javascript and thus send unvalidated data to the database?

external data can be anything and can come from anywhere. you must validate data on the server before using it.

your form processing code should -

  1. detect that a post method form was submitted.
  2. trim, than validate all inputs, storing validation errors in an array, using the field name as the array index.
  3. if there are no errors (the errors array is empty), use the submitted data.

I suggest that for a user friendly page you validate in both places. With Javascript the user will not have to wait for the server in order to find out there was an entry error. Very annoying. Then validate again before placing it into the database in case a user is trying to hack it.

your posted code has one technical issue, in that it only stores the last validation error in the $error variable, so, if there are multiple validation errors, you would only see the last error message. using an array to hold the error messages will solve this, and using the field name as the array index will let you test for and display the messages adjacent to the fields they belong with. i recommend  displaying any error above or next to the field, rather than below it, in case the field is at the bottom of the screen and anything below it might not get seen.

does your posted code operate as i have described above or does it appear to insert empty values when you don't enter anything in the form fields? if so, i suspect that your html markup has some white-space as the field value attributes, which won't be considered as empty(). correcting the html mark would correct this, but trimming the data as suggested would handle the case where a visitor accidentally enters space character(s) in a required field.

do you have a specific question, problem, or error concerning the suggestions?

 

From what I've learned, server validation (with PHP) is the safeguard. 

Client-side (like JS) is prettier and more user friendly, but also unreliable since it can be easily altered or removed.

Use both as applicable and practical.

 

As for your actual issue, there are likely several approaches that could be useful.

To me, the most obvious would be that you are using a variable $error.

$error has several messages depending on the input you are validating. 

It seems to be an exciting constant throughout your script. Do why not utilize it with something like

 

 

 

Quote

// assign variables

$error = "";  //at TOP with other variables

 ////your validations

if($error != "") {

echo "Fix the ERROR that exists";

             } else {

////process data

 

Essentially, your trolling PHP that every error provides a message, so unless there are no messages, do not process.

If $error is empty (the way it started without being diverted) then there are no messages, which means no errors, and it's then safe to proceed.

You can use a similar technique with JavaScript.

Maybe build an array for errors

 

$errors = [];
// This is the attempted validation code
if(empty($firstname)) {
	$errors[] = "- Please enter your firstname";
}
if(empty($email)) {
	$errors[] = "- Please enter your email";
}

if (!empty($errors)) {
	$result="<p class='alert error'>There is an error. Please correct the following:";
	$result =. implode("<br />", $errors);
	$result =. "</p>";
} else {
//....
}

echo $result;

 

Untested code but should give you the idea

 

EDIT: i always validate server side, but add client side validation to improve UX

Edited by MadTechie
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.