1

I am trying to insert form field values after validating the form. I develope a seperate php file validate1.php to insert the form field values in database and another file describing form and its validation is in connection.php

When I run connection.php, form fields are getting validated only once,and after form is submitted after that i enter anything.Which should not be happened.

My connection.php is

<html>
<head>
    <title></title>
    <style> .error {color:#ff0000;} </style>
</head>
<body>
    <?php 
        $companyNameErr = $addressErr = $emailErr = $contactErr = "";
        $companyName = $address = $email = $contact = $description = "";
        function test_data($data)
        {
            $data=trim($data);
            $data=stripslashes($data);
            $data=htmlspecialchars($data);
            return $data;
        }

        $errors = array();
        if ( $_SERVER["REQUEST_METHOD"] =="POST" )
        {
            $companyName=$_POST["companyName"];
            if( empty($companyName) )
            {
                $companyNameErr = "Please Enter Company Name";
                $errors[]= $companyNameErr ;
            }
            else
            {
                if( !preg_match("/^[a-zA-Z ]*$/",$companyName) )
                {
                    $companyNameErr = "Invalid Company Name";
                    $errors[]= $companyNameErr ;
                }
                else
                {
                    $companyName=test_data($companyName);
                }
            }
            $address=$_POST["address"];
            if( empty($address) )
            {
                $addressErr = "Please Enter Address";
                $errors[]= $addressErr ;
            }
            else
            { 
                $address=test_data($address);
            }
            $email=$_POST["email"];
            if( empty($email) )
            {
                $emailErr = "Please Enter Email";
                $errors[]= $emailErr ;
            }
            else
            {
                if( !filter_var($email, FILTER_VALIDATE_EMAIL) )
                {
                    $emailErr = "Invalid Email";
                    $errors[]= $emailErr ;
                }
                else
                {
                    $email=test_data($email);
                }   
            }       
            $contact=$_POST["contact"];
            if( empty($contact) )
            {
                $contactErr = "Please Enter Contact Number";
                $errors[]= $contactErr ;
            }
            else
            { 
                if( !preg_match("/^[0-9]*$/",$contact ) )
                {
                    $contactErr = "Invalid Contact";
                    $errors[]= $contactErr ;
                }
                else
                {
                    $contact=test_data($contact);
                }   
            }
    }
    ?>
    <form name="myform" method="post" action="<?php if(empty($errors)){ echo $_SERVER["PHP_SELF"]; }else{ echo "validate1.php"; }?>" >
        <table>
            <tr>
                <td>Company Name</td>
                <td><input type="text" name="companyName" value ="<?php if(isset($_POST['companyName']) && empty($companyNameErr)){ echo $_POST['companyName'];} else {echo '';}?>" required ><span class="error"><sup>*</sup><?php echo $companyNameErr; ?></span></td>
            </tr>
            <tr>
                <td>Address</td>
                <td><input type="text" name="address" value ="<?php if(isset($_POST['address']) && empty($addressErr)){ echo $_POST['address'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php echo $addressErr; ?></span></td>
            </tr>
            <tr>
                <td>Email</td>
                <td><input type="text" name="email" value ="<?php if(isset($_POST['email']) && empty($emailErr)){ echo $_POST['email'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php echo $emailErr; ?></span></td>
            </tr>
            <tr>
                <td>Contact</td>
                <td>+91-<input type="text" name="contact" value ="<?php if(isset($_POST['contact']) && empty($contactErr)){ echo $_POST['contact'];} else {echo '';}?>" required maxlength="10" minlength="10"><span class="error"><sup>*</sup><?php echo $contactErr; ?></span></td>
            </tr>
            <tr>
                <td>Description</td>
                <td><textarea name="description" cols="60" rows="3"></textarea></td>
            </tr>
        </table>
        <input type="submit" name="submit" value="submit">
    </form>
</body>

and Validate1.php is

<html>
<head>
    <title></title>
</head>
<body>    
<?php 
    $servername="localhost";
    $username="root";
    $password="";
    $conn = new mysqli($servername, $username, $password, 'mydatabase');
    if ($conn->connect_error)
    {
        die("Connection failed: " . $conn->connect_error);
    }
    $conn->query("CREATE DATABASE IF NOT EXISTS `MyDataBase`"); 
    $conn->query("CREATE TABLE IF NOT EXISTS MyDataBase.company_details( `comp_id` INT AUTO_INCREMENT PRIMARY KEY,`company_name` VARCHAR(50) NOT NULL,`address` VARCHAR(70) NOT NULL,`email` VARCHAR(30) NOT NULL,`contact` INT(13) NOT NULL,`description` VARCHAR(150))");
    $conn->query("INSERT INTO company_details (company_name, address, email, contact, description ) VALUES ( '".$_POST['companyName']."', '".$_POST['address']."', '".$_POST['email']."', '".$_POST['contact']."', '".$_POST['description']."')");
    $conn->close();
?>
</body>

  • May i show your HTML Code. – Asheesh May 02 '16 at 07:56
  • Yes I mentioned above – Yogesh Bhardwaj May 02 '16 at 08:06
  • first time errors array empty and action is self where u check for errors if errors found then action is validation1 now validation1 has no code for validation and u add no text inside validation that's reason nothing appears – Maninderpreet Singh May 02 '16 at 08:09
  • I corrected. Thanx Maninderpreet Singh But a new question arises in front of me. now form gets submit in two click when all fields are correct. Can You tell me why does this happen – Yogesh Bhardwaj May 02 '16 at 12:03
  • i don't get notification of ur comment – Maninderpreet Singh May 02 '16 at 12:18
  • [Little Bobby](http://bobby-tables.com/) says [your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard May 02 '16 at 13:03

1 Answers1

0

Try the following code

N:B : Make sure you have used sql injection prevention techniques when posting form data.

connection.php

<?php 
session_start();

    $companyName = $address = $email = $contact = $description = "";
    function test_data($data)
    {
        $data=trim($data);
        $data=stripslashes($data);
        $data=htmlspecialchars($data);
        return $data;
    }

    $_SESSION['error'] = array();
    $_SESSION['resend'] = array();
    if ( $_SERVER["REQUEST_METHOD"] =="POST")
    {
        $companyName=$_POST["companyName"];
        if(empty($companyName) )
        $_SESSION['error']['companyNameErr'] = "Please Enter Company Name";
        else
        {
            if( !preg_match("/^[a-zA-Z ]*$/",$companyName) )                
                $_SESSION['error']['companyNameErr'] = "Invalid Company Name";                
            else
                $_SESSION['resend']['companyName'] = test_data($companyName);                
        }

        $address=$_POST["address"];
        if(empty($address) )            
            $_SESSION['error']['addressErr'] = "Please Enter Address";            
        else
            $_SESSION['resend']['address'] = test_data($address);

        $email=$_POST["email"];
        if(empty($email))            
            $_SESSION['error']['emailErr'] = "Please Enter Email";
        else
        {
            if( !filter_var($email, FILTER_VALIDATE_EMAIL) )                
                $_SESSION['error']['emailErr'] = "Invalid Email";
            else
                $_SESSION['resend']['email'] = test_data($email);                    
        }

        $contact=$_POST["contact"];
        if(empty($contact))
            $_SESSION['error']['contactErr'] = "Please Enter Contact Number";                
        else
        { 
            if( !preg_match("/^[0-9]*$/",$contact ) )                
                $_SESSION['error']['contactErr'] = "Invalid Contact";
            else                
                $_SESSION['resend']['contact'] = test_data($contact);                   
        }

        $description=$_POST["description"];
        $_SESSION['resend']['description'] = test_data($description); 

        if(empty($_SESSION['error'])){
            header('location:validate1.php');    
        exit;
        }
    }
?>
<html>
<head>
    <title></title>
    <style> .error {color:#ff0000;} </style>
</head>
<body>

    <form name="myform" method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" >
        <table>
            <tr>
                <td>Company Name</td>
                <td><input type="text" name="companyName" value ="<?php if(isset($_SESSION['resend']['companyName']) && empty($_SESSION['error']['companyNameErr'])){ echo $_SESSION['resend']['companyName'];} else {echo '';}?>" required ><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['companyNameErr'])) echo $_SESSION['error']['companyNameErr']; ?></span></td>
            </tr>
            <tr>
                <td>Address</td>
                <td><input type="text" name="address" value ="<?php if(isset($_SESSION['resend']['address']) && empty($_SESSION['error']['addressErr'])){ echo $_SESSION['resend']['address'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['addressErr'])) echo $_SESSION['error']['addressErr']; ?></span></td>
            </tr>
            <tr>
                <td>Email</td>
                <td><input type="text" name="email" value ="<?php if(isset($_SESSION['resend']['email']) && empty($_SESSION['error']['emailErr'])){ echo $_SESSION['resend']['email'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['emailErr'])) echo $_SESSION['error']['emailErr']; ?></span></td>
            </tr>
            <tr>
                <td>Contact</td>
                <td>+91-<input type="text" name="contact" value ="<?php if(isset($_SESSION['resend']['contact']) && empty($_SESSION['error']['contactErr'])){ echo $_SESSION['resend']['contact'];} else {echo '';}?>" required maxlength="10" minlength="10"><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['contactErr'])) echo $_SESSION['error']['contactErr']; ?></span></td>
            </tr>
            <tr>
                <td>Description</td>
                <td><textarea name="description" cols="60" rows="3"><?php if(isset($_SESSION['resend']['description'])) echo $_SESSION['resend']['description'];?></textarea></td>
            </tr>
        </table>
        <input type="submit" name="submit" value="submit">
    </form>
</body>
</html>

Validate1.php

<?php 
session_start();

if(isset($_SESSION['resend'])){ 
    $servername="localhost";
    $username="root";
    $password="";
    $conn = new mysqli($servername, $username, $password, 'test');
    if ($conn->connect_error)
    {
        die("Connection failed: " . $conn->connect_error);
    }
    //$conn->query("CREATE DATABASE IF NOT EXISTS `MyDataBase`"); 
    $conn->query("CREATE TABLE IF NOT EXISTS test.company_details( `comp_id` INT AUTO_INCREMENT PRIMARY KEY,`company_name` VARCHAR(50) NOT NULL,`address` VARCHAR(70) NOT NULL,`email` VARCHAR(30) NOT NULL,`contact` INT(13) NOT NULL,`description` VARCHAR(150))");
    $result = $conn->query("INSERT INTO company_details (company_name, address, email, contact, description ) VALUES ( '".$_SESSION['resend']['companyName']."', '".$_SESSION['resend']['address']."', '".$_SESSION['resend']['email']."', '".$_SESSION['resend']['contact']."', '".$_SESSION['resend']['description']."')");
    $conn->close();
    unset ($_SESSION['resend']);
    unset ($_SESSION['error']);
    header('location:connection.php'); 
    exit;
}
?>
<html>
<head>
    <title></title>
</head>
<body>   

</body>
</html>
Mohammedshafeek C S
  • 1,916
  • 2
  • 16
  • 26