1

I want to make a simple form which displays error if a field has not been inputted. I don't know how to do it. Here's my code: php code:

<?php

    //include the connection file

    require_once('connection.php');

    //save the data on the DB and send the email

    if(isset($_POST['action']) && $_POST['action'] == 'submitform')
    {
        //recieve the variables

        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
        $ip = gethostbyname($_SERVER['REMOTE_ADDR']);

        //save the data on the DB

        mysql_select_db($database_connection, $connection);

        $insert_query = sprintf("INSERT INTO feedback (name, email, message, date, ip) VALUES (%s, %s, %s, NOW(), %s)",
                                sanitize($name, "text"),
                                sanitize($email, "text"),
                                sanitize($message, "text"),
                                sanitize($ip, "text"));

        $result = mysql_query($insert_query, $connection) or die(mysql_error());

        if($result)
        {
            //send the email

            $to = "[email protected]";
            $subject = "New message from the website";

            //headers and subject
            $headers  = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
            $headers .= "From: ".$name." <".$email.">\r\n";

            $body = "New contact<br />";
            $body .= "Name: ".$name."<br />";
            $body .= "Email: ".$email."<br />";
            $body .= "Message: ".$message."<br />";
            $body .= "IP: ".$ip."<br />";

            mail($to, $subject, $body, $headers);

            //ok message

            echo "Your message has been sent";
        }
    }

    function sanitize($value, $type) 
    {
      $value = (!get_magic_quotes_gpc()) ? addslashes($value) : $value;

      switch ($type) {
        case "text":
          $value = ($value != "") ? "'" . $value . "'" : "NULL";
          break;    
        case "long":
        case "int":
          $value = ($value != "") ? intval($value) : "NULL";
          break;
        case "double":
          $value = ($value != "") ? "'" . doubleval($value) . "'" : "NULL";
          break;
        case "date":
          $value = ($value != "") ? "'" . $value . "'" : "NULL";
          break;
      }

      return $value;
    }
    ?>

<form id="ContactForm" method="post" action="mail.php">
                            <div class="wrapper"><input class="input" name="name" id="name" type="text" value="Name:" onBlur="if(this.value=='') this.value='Name:'" onFocus="if(this.value =='Name:' ) this.value=''" ></div>
                            <div class="wrapper"><input class="input" name="email" id="email" type="text" value="E-mail:" onBlur="if(this.value=='') this.value='E-mail:'" onFocus="if(this.value =='E-mail:' ) this.value=''" ></div>
                            <div class="textarea_box"><textarea cols="1" rows="1" onBlur="if(this.value=='') this.value='Message:'" onFocus="if(this.value =='Message:' ) this.value=''" >Message:</textarea></div>
                            <input type="hidden" id="action" name="action" value="submitform" />
                            <input type="submit" class="button" id="submit" name="submit" value="Submit" /> <input type="reset" class="button" id="reset" name="reset" value="Reset" />
                        </form>
3
  • 1
    you can validate your form using php on the server side but I would recommend using javascript/jQuery to validate the form inputs before the form is submitted and then also checking server side with PHP. There are loads of jQuery form validation plugins that make it really simple and easy to do. Commented May 31, 2012 at 14:01
  • 2
    @martincarlin87 Well, i prefer doing the checks server side. Because not every client enabled javascript... Commented May 31, 2012 at 14:02
  • 1
    yes, but as I said, you can do BOTH. Commented May 31, 2012 at 14:06

2 Answers 2

1

Before saving the information into the database check to see if each submitted value contains valid data. If not, put the field name into an array. Once validation is complete check to see if the array is empty or not. If it is empty, save the info into your database. If it is populated re-display the form, populated with the submitted data, and an easy-to-read notice of what errors they made so they know what to fix.

Some PHP functions to look into are: filter_var(), ctype_*, and empty()

FYI, you should consider migrating away from mysql_* functions since they will soon be going away.

Sign up to request clarification or add additional context in comments.

Comments

0

To achieve this, you should create a code block that does an empty check (since that is the only thing you want to check for). A simple code snippet is given below:

function checkFormErrors($name,$email,$message){
    //now we define a function to check for errors
    $errors = array();
    //define an error container
    if(empty($name)){
        //check the name field
        $errors[] = "You need to enter a name";
    }
    if(empty($email)){
        //check the email field
        $errors[] = "You need to enter an email address";
    }
    .... //do more checks for all fields here
    return $errors;
}
if(isset($_POST['action']) && $_POST['action'] == 'submitform'){
    //recieve the variables
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $ip = gethostbyname($_SERVER['REMOTE_ADDR']);

    $errors = checkFormErrors($name,$email,$message);
    //check for errors
    if(empty($errors)){
        //continue with the processing you did above
        .....
    }
}


In you HTML file/page, you then need to put this above the form (feel free to style it
with css)
<?php
    if(isset($errors)){
        //the variable exists
        echo implode("<br />", $errors);
    }
?>

I put up a blog post here and also have some scripts that can help with form validation

Hope this helps!

1 Comment

So far the form has been working. I've changed the form to avoid SQL injections and edited it a great deal( from various blogs and sources). But now i wanted to encode the password in md5. I'm trying adding "md5['password']" but it shows an error. My php code is:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.