Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Empty Form Field Validation?

  • This topic is empty.
Viewing 15 posts - 31 through 45 (of 58 total)
  • Author
    Posts
  • #159873
    MBM
    Participant

    Didn’t work.

    #159875
    chrisburton
    Participant

    Try

    <?php 
        echo '<pre>';
        print_r($_POST);
        echo '</pre>'; 
    ?>
    
    #159877
    MBM
    Participant

    Yields :

    Array
    (
    )

    #159878
    Alen
    Participant

    What exactly didn’t work? Did you receive error? Are you posting to the same page, in your code you set new location, but you try to echo $message from current document.

    #159879
    MBM
    Participant

    The validation is supposed to display an error message when a user leaves a blank field in a form. The form has 5 inputs :

    Forename
    Surname
    Username
    Password
    email

    If the user only fills in the forename and surname field the php should show all these errors in the form :

    Please enter a username
    Please enter a password
    Please enter your email address

    If they fill in everything but miss out the password field it should show :

    Please enter a password.

    It’s like any form you see on a website, if you don’t fill in one of the fields an error message is (should!) be displayed.

    #159881
    Alen
    Participant

    the error messages are displayed in the address bar and not the page itself.

    This is expected, since you are sending the data via:

    if( $errmessage )
    {
      $message = implode( "<br>", $errmessage );
      header( "Location: https://mywebsite.com/register2.php?message=$message" );
    }
    

    message=$message -> $message will not be a variable. It will be a text string containing data from $errmessage.

    Anything after the ? is a variable, anything after = is data that is passed. So the variable $message is not what you should be getting, it’s the ?message part.

    So to make it more clear.

    some-page.php?variable=my cool variable data

    echo $_GET["variable"];would give you “my cool variable data”

    #159882
    Alen
    Participant
    /* Index Page, posting to register.php */
    
    <form action="register.php" type="post">
        <input type="text" name="variable">
        <input type="submit">
    </form>
    
    /* Register Page, echoing value */
    
    <?php echo $_GET["variable"]; ?>
    

    So if we type “csstricks” in the input field, our data on register.php page would be csstricks and address bar would look like this: register.php?variable=csstricks

    Hopefully that doesn’t confuse you even more.

    #159889
    MBM
    Participant

    Thanks for the explanation. I understand variables, arrays I do not!

    Anything after the ? is a variable, anything after = is data that is passed.

    So this passes the array through the variable message?

    header( “Location: https://mywebsite.com/register2.php?message=$message&#8221; );

    <?php echo $_GET["message"]; ?>

    Almost there. All five error messages are displayed regardless of how many empty fields there are!

    Also why is it :

    and not

    $message is a variable so is message an array?

    #159890
    Alen
    Participant

    No the data after = will be string data, not array, since you are imploding the array…

    $data = array('one', 'two', 'three');
    $data_out = implode('<br>', $data);
    header('Location: register.php?variable=' . $data_out);
    exit;
    
    /*
    
      register.php?variable=one<br>two<br>three
    
    */
    

    So when using <?php echo $_GET["variable"]; ?> you would get

    one<br>two<br>three in your html which will display as:

    one
    two
    three

    #159893
    __
    Participant

    I’ve debugged the code but it’s still not working as it should, the error messages are displayed in the address bar and not the page itself.

    I’ve tried : <?php print $message ; ?> To display the messages.

    To be clear, where did you try this? In the last gist you linked to, this code was on the same page that you used to validate the form. Is all of your code on the same page?

    If so, you don’t need to redirect the user. In doing so, you are leaving the page (along with all the variables and messages you’ve made) and coming back to it new. As @Alen has pointed out, $_GET['message'] will contain your error message, but $message will be empty.

    If you don’t need to redirect to a different page, then you don’t need to redirect at all: just display the message when you get to the bottom of the script. For example, you might have a program flow like this:

    <?php
    if( /* form was submitted */ ){
        if( /* form field is empty */ ){
            $errMessage[] = "error message";
        }
        //  etc ...
    
        if( /* errors */ ){
            $message = implode( "<br>",$errMessage );
        }
        else{
            /* connect to database */
            if( /* data insert successful */ ){
                $message = "success message";
            }
            else{
                $message = "failure message";
            }
        }
    }
    ?><form>
        <?php if( /* there is a message */ ){ print "<p>$message</p>"; } ?>
        <input ...>
        etc ...
    </form>
    

    Sorry I didn’t notice this earlier. I assumed you were redirecting to a different page. Note that if you don’t follow what’s going on here, you can still make your current approach work; it’s just a little round-about. Keep this in mind in the future, though.

    #159908
    MBM
    Participant

    I’ve updated the gist. I had in the form and also added it after the validation statements :

    if($formValue['email']==""){
            $errmessage[] = "Please enter your email address" ;
        }
    if( $errmessage ){$message = implode( "<br>",$errmessage ); 
    echo $_GET["message"];
    

    But it doesn’t execute, it creates a new record.

    https://gist.github.com/gyprosetti/f9606ea721650f4756be

    Sorry I didn’t notice this earlier. I assumed you were redirecting to a different page. Note that if you don’t follow what’s going on here, you can still make your current approach work; it’s just a little round-about. Keep this in mind in the future, though.

    I will learn PDO in the summer. I have looked at mysqli and the online manual is, for me, very poorly written and overly complicated. PDO statements make more sense to me but there isn’t a great deal of material online so I plan on buying Learning PHP Data Objects: A Beginner’s Guide and working my way through that. Once I can do everything I need to do in mysql I will learn how to recode the statements in pdo. I’ve got a statistical database with over 10,000 records that I have been wanting to make available through one of my websites for years so will use pdo for that! There will not be a login process just a series of queries that visitors will be able to run so at least I won’t have to worry about validation.

    #159915
    __
    Participant

    I wasn’t prodding about mysqli/pdo, I promise. I was asking if you were redirecting to the same page or a different page. It’s starting to look like this is all on the same page and, if so, there’s no real need to redirect.

    #159917
    MBM
    Participant

    Yes it’s all on the same page. When they register and miss out a field I want the errors on the same page.

    I do want to learn PDO for the stats database, there’s no point in going to the trouble of making a database with thousands of records available if the php is written in something that is or will be soon redundant. For the project I’m working on now it doesn’t really matter what it’s written in as I’m building on something I started years ago to help me understand php, no one is going to see it.

    #160169
    MBM
    Participant

    I’ve followed a tutorial and every field validates independently. The problem now is I cannot get the insert statements to execute. This is the last field and the returns the data :

      if (empty($_POST["email"]))
         {$emailErr = "Enter your email address";}
       else
         {$email = validate_input($_POST["email"]);}
    }
    function validate_input($data)
    {
         $data = trim($data);
         $data = stripslashes($data);
         $data = htmlspecialchars($data);
         return $data;
    }
    

    How do I then combine the above with this? Do I need the redirects?

    $Link = mysql_connect($Host, $User, $Password);
    $Query = "INSERT INTO $Table_2 VALUES ('0','".mysql_escape_string('forename')."','".mysql_escape_string("surname")."', '".mysql_escape_string("username")."', '".mysql_escape_string("password")."', '".mysql_escape_string("email")."')";
    if(mysql_db_query ($DBName, $Query, $Link)){
    $message = "You have successfully registered";
    header("Location: register2.php?message=$message");
    }else{
    $message = "You've Broke It!";
    die(mysql_error());
    header("Location: register2.php?message=$message");
    }
    ?>
    

    This gives a redirect loop error.

    Here’s the gist.

    https://gist.github.com/gyprosetti/154acb19dd16197077e5

    #160178
    __
    Participant
    function validate_input($data)
    {
         $data = trim($data);
         $data = stripslashes($data);
         $data = htmlspecialchars($data);
         return $data;
    }
    

    This, and functions like it, are not good. Your previous code was much better. Here’s the problem:

    • Doesn’t validate anything. Performs some sanitization; however:
    • Assumes magic_quotes_gpc are enabled. If they are, you should simply turn them off in your php.ini. If they are not, then doing this can actually cause more problems.
    • Assumes you’re printing the input back out to the user. If you aren’t (say you’re sending a JSON response, or saving to a database), then htmlspecialchars will just cause confusion down the road.

    In short, you need to know what you are going to do with the data before you validate/sanitize it. What you need to do will depend on the sort of data it is (e.g., is it an email address? formatted text? a number?) and what you intend to do with it (e.g., are you printing it? saving in a database? using as input for a function?).

    The problem now is I cannot get the insert statements to execute.

    It is likely that the call to htmlspecialchars is generating semicolons (;) in your data (because that’s what it’s supposed to do), which are causing errors in your mysql statements (because a semicolon ends an SQL statement).

    This gives a redirect loop error.

    What do you mean by “redirect loop error”? The code you posted only redirects if the SQL query was successful, and you say that it is not.

    You’re printing mysql_error. What does it say?

    Also, I understand that you want to continue using the mysql_* functions for now, but note that some functions are not only deprecated, but outright broken. mysql_escape_string, for example, does not respect the DB connection character set and was never safe to use. At a bare minimum, you need to use mysql_real_escape_string. Likewise, the manual explicitly says “do not use” mysql_db_query. It was replaced with the functions mysql_select_db and mysql_query, in the year 2000, because it was broken.

    I’m sorry to be stubborn about this, but this is the only advice I can offer: don’t use old, broken functions. There is no way to make them “work.”

    I think we’re floundering, here: we’ve been talking about a lot of things, adding and removing stuff, but it’s not “coming together.” I wrote a new version of your script so you can see the “whole picture” of what I am trying to describe, kinda like a tutorial. If you’d like to use it, you are welcome to. If you have any questions please ask.

    Sorry I couldn’t be more helpful.

Viewing 15 posts - 31 through 45 (of 58 total)
  • The forum ‘Back End’ is closed to new topics and replies.