3

Ok friends I am very confused with this basic thing. I have read lot of posts where it says, I need to add SELF POST or something but I am not understanding.

I have two files, index.html and submit.php. index.html has a form with a submit button by clicking which, the submit.php file is called and shows a message "1 record added". I want to redirect back from the submit.php file to index.html file. I dont know what I am doing wrong. Is it because one is html file and another php? Please help. Here is my code

index.html file

<form method="post" action="submit.php">

submit.php file

    <?php
    $con = mysql_connect("localhost","myuser","mypassword");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    mysql_select_db("mydb", $con);
    $sql="INSERT INTO members (sName, sCity, sMobile, sEmail, sSub, sSlogan)
    VALUES ('$_POST[name]', '$_POST[city]', '$_POST[mobile]', '$_POST[email]', '$_POST[sub]', '$_POST[slogan]')";
    if (!mysql_query($sql,$con))
      {
      die('Error: ' . mysql_error());
      }
    echo "1 record added";
    mysql_close($con)
    ?>
    </body>
</html>

EDIT

Please find code of index.html and submit.php file. With your help, both are working perfect. I am still struggling where excatly to put the validation code. i am using html5 input types in html file and I dont know where exactly the validation to happen in submit.php file. Yes, I do have multiple forms and I made validations.php file as suggested by you. What I am not understanding is if you have function validate_name($input) for name field in validations.php file then why are you validating name again in submit.php? ( if (!empty($_POST['name']) ). I am also not understanding where will the error messages been shown? If I try to add these functions, it gives me blank page on clicking submit and the data does not go to database.

Can you suggest a location in the submit.php file where I should add these validations by editing my submit.php file? Regexp for email ('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/') Regexp for phone (^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$)

This is my index.html file

<!DOCTYPE HTML>
<html>

<head>
    <title>My Title</title>
</head>

<body>

    <form method="post" action="submit.php">
        <div class="box">
            <div class="cl"><input type="text" name="name" placeholder="Name" /></div>
            <div class="cl"><input type="text" name="city" placeholder="City" /></div>
            <div class="cl"><input type="text" name="mobile" placeholder="Mobile" /></div>
            <div class="cl"><input type="email" name="email" placeholder="Email" /></div>
            <div class="cl"><input type="text" name="sub" placeholder="Want 3 m Free Subscription (Yes/No)?"></textarea></div>
            <div class="cl"><input type="text" name="slogan" placeholder="Suggest a slogan for 6 m subscription"></textarea></div>
        </div>

        <div class="srow">
            <div class="cl1">
                <ul class="action">
                    <li><input type="submit" value="Submit" /></li>
                </ul>
            </div>
        </div>
    </form>
</body>

</html>

This is the submit.php file help that I took from you

<?php
include 'config.php'; // store your configuration in a seperate file so 
                      // you only need to update it once when your environment changes

$errors = false;
$output = '';
$nl = '<br>'.PHP_EOL;
$redirect_url = 'index.html';

if (!$con = new mysqli(DBHOST,DBUSER,DBPASS,DBNAME)){
    $errors = true;
    $output .= "ERROR Can't connect to DB".$nl;
};   


if (!$errors){
   //should validate/clean $_POST before using in query
   $name = $con->escape_string($_POST['name']);
   $city = $con->escape_string($_POST['city']);
   $email = $con->escape_string($_POST['email']);
   $mobile = $con->escape_string($_POST['mobile']);
   $sub = $con->escape_string($_POST['sub']);
   $slogan = $con->escape_string($_POST['slogan']);

   $sql="INSERT INTO members 
            (sName, sCity, sMobile, sEmail, sSub, sSlogan)
         VALUES ('$name', '$city', '$mobile', '$email',
                '$sub','$slogan')";

   if (!$con->query($sql)){ //forgot a parenthesis here earlier
      $output .= 'ERROR: DB said: ('.$con->errno.') '.$con->error.$nl;
      $output .= 'Query was:'.$sql.$nl;
      $errors = true;
   }else{
     $output .= "1 record added".$nl;
   }
}

if (!$errors){
   //if there are no errors redirect to index.html;
   header('refresh: 2; URL='.$redirect_url);
   $output .= '...Redirecting...'.$nl;
}else{
   //show the errors and allow display a link to go back/try again
   $output .= '<a href="'.$redirect_url.'">Try again</a>'.$nl;
}
echo $output;
?>

PS: One thing I observed is that html5 (input type="email") shows invalid email alert immediately after you go to next field, just under the field. How is it possible to do it for all fields? (something like a validation check on field lost focus)

Thanks

Community
  • 1
  • 1
Sabha
  • 621
  • 10
  • 32
  • Where is your redirect? – Epodax Sep 15 '15 at 12:20
  • First of all read about sql injection. Second - mysql is deprecated, use mysqli or PDO instead. Third - rename index.html to index.php, in submit.php after mysql_close($con) add header("Location: http://localhost/index.html?success=1 (or what url do you have)"). In index.php add 1 record added – SevStryker Sep 15 '15 at 12:26
  • you have a syntax error and you most likely are outputting before header – Funk Forty Niner Sep 15 '15 at 12:54

3 Answers3

1

You can have your submit script check for a failure and redirect to the index.html for adding more on success.

Bear in mind that you'll have to set the header before you output any other data with echo.

header('refresh: 3; URL=index.html');

Don't use mysql, use mysqli or PDO.

Learn about SQL injection.

So your sumbit.php might look like:

<?php
include 'config.php'; // store your configuration in a seperate file so 
                      // you only need to update it once when your environment changes

$errors = false;
$output = '';
$nl = '<br>'.PHP_EOL;
$redirect_url = 'index.html';

$con = new mysqli(DBHOST,DBUSER,DBPASS,DBNAME);

if ($con->connect_errno){
    $errors = true;
    $output .= "ERROR Can't connect to DB".$nl;
};

if (!$errors){
   //should validate/clean $_POST before using in query
   $name = $con->escape_string($_POST['name']);
   $city = $con->escape_string($_POST['city']);
   $email = $con->escape_string($_POST['email']);
   $mobile = $con->escape_string($_POST['mobile']);
   $sub = $con->escape_string($_POST['sub']);
   $slogan = $con->escape_string($_POST['slogan']);

   $sql="INSERT INTO members 
            (sName, sCity, sMobile, sEmail, sSub, sSlogan)
         VALUES ('$name', '$city', '$mobile', '$email',
                '$sub','$slogan')";

   if (!$con->query($sql)){ //forgot a parenthesis here earlier
      $output .= 'ERROR: DB said: ('.$con->errno.') '.$con->error.$nl;
      $output .= 'Query was:'.$sql.$nl;
      $errors = true;
   }else{
     $output .= "1 record added".$nl;
   }
}

if (!$errors){
   //if there are no errors redirect to index.html;
   header('refresh: 2; URL='.$redirect_url);
   $output .= '...Redirecting...'.$nl;
}else{
   //show the errors and allow display a link to go back/try again
   $output .= '<a href="'.$redirect_url.'">Try again</a>'.$nl;
}
echo $output;

config.php would contain

define('DBHOST','localhost');
define('DBUSER','myuser');
define('DBPASS','secretpass');
define('DBNAME','mydb');

EDIT / ADDITIONAL:

If you want to do some validation, it is helpful to do some on the client so that your users won't have to submit and get rejected when you can already know that some inputs don't comply.

But you will also need to validate on the server side (bad users can circumvent any client side validation you may have by editing the html in their browser)

To help your users, you can use some of the new html5 input types available, optionally with some additional javascript:
e.g. <input type="email" name="email">

Your index.html can stay as a static page. It just presents the input form and maybe loads some javascript resources for validation.

Your validation should happen in submit.php. If you're going to have more forms in your application you might consider having your server-side validation functions in a separate validations.php that you can include in your submit.php

It could contain functions like:

function validate_name($input){
    // fairly naive rule:
    // upper and lower case latin characters and space
    // at least three character long
    // you may want to look at allowing other characters such as é ö etc.
    $input = trim($input); //get rid of spaces at either end
    if (preg_match('/^[a-zA-Z ]{3,}$/',$input) == 1){
        return $input;
    }else{
        return false;
    }
}

In your submit.php you could then have

...
include_once 'validations.php';
...

  if (!empty($_POST['name'])){
    if (!$name = $con->escape_string(validate_name($_POST['name'])){
        $errors = true;
        $output .= 'ERROR: Invalid Name: '.$_POST['name'].$nl;
    }
  }else{
    $errors = true;
    $output .= 'ERROR: No name specified'.$nl;
  }

  if (!empty($_POST['city']){
    ...

...

To get the data already entered to populate in case of failure you can send the data back to the original via GET parameters.

In submit.php, near the end you could add something like ...

if (!$errors){
   //if there are no errors redirect to index.html;
   header('refresh: 2; URL='.$redirect_url);
   $output .= '...Redirecting...'.$nl;
}else{
   //show the errors and allow display a link to go back/try again
   //add parameters to show the data already entered
   $redirect_url .= '?'.
        http_build_query(
                  array('name'=>$name,
                        'city'=>$city,
                        'mobile'=>$mobile,
                        ...
         ));

   $output .= '<a href="'.$redirect_url.'">Try again</a>'.$nl;
}
echo $output;

and in index.php you'll have to read them in and set the values in your input fields if they exist.

<?php 
//we'll use urldecode() so that any special characters will be interpreted correctly
if (!empty($_GET['name'])){
    $name = urldecode($_GET['name']);
}else{
    $name = '';
}
if (!empty($_GET['city'])){
    $city = urldecode($_GET['city']);
}else{
    $city = '';
}
....
?>
<input type="text" name="name" value="<?php echo $name; ?>"/>
<input type="text" name="city" value="<?php echo $city; ?>"/>
Loopo
  • 2,204
  • 2
  • 28
  • 45
  • Thank you for your reply. This is driving me crazy. I did exactly the way you said but it just presents a blank submit.php file and the data does not go in the database, no alerts, no redirection, nothing... I checked it three times. I dont know what I am doing wrong. Do I need to put html body and other tags in the submit.php file? All my files (index.html, submit.php and config.php are in the same folder) – Sabha Sep 15 '15 at 13:17
  • Edited my answer. I forgot to close one bracket in after the $con->query($sql) ... also added escaping for all POST fields. It's working for me now at least. – Loopo Sep 15 '15 at 13:45
  • Took me a little while to understand which close bracket you were talking but finally understood. Its working now. Thanks for your help – Sabha Sep 15 '15 at 14:04
  • As advised by you, I was trying script check for a failure with few validation before redirecting to index.html but struggling with that. I have a regexp for email ('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/') and phone (^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$) but dont know how to get this right. Dont know whether to do it client side or server side and the syntax. I changed the index.html to index.php with – Sabha Sep 17 '15 at 07:21
  • Thanks once again for your help but I am still finding it a bit difficult and wish to know where exactly to add the validations. I have edited my original post. Appreciate if you could have a look at it. Thanks – Sabha Sep 19 '15 at 12:08
  • I think validation should be a separate question. – Loopo Sep 20 '15 at 13:07
  • I posted a separate question here http://stackoverflow.com/questions/32695491/validate-fields-on-html-page-with-php. Appreciate if you can shed some light on my queries. Thanks – Sabha Sep 21 '15 at 13:20
  • Please help. everything is working but the moment I add if (!empty($_POST['name']){ in submit.php, I get a blank page and record is not getting added in the database. If I remove the validation, everything works fine. I have made validations.php file with the validate_name($input) function you gave and included in the submit.php file. Can you tell me where to add the validation if (!empty($_POST['name']){ in submit.php? Can you please update your submit.php code with validation?As advised by you, I posted a separate question for validation. Thanks – Sabha Sep 22 '15 at 08:46
  • If you're getting a blank page during development, you should probably turn on [error reporting](http://stackoverflow.com/a/21429652/32763) on your server so that you can see better what's going on... either in your php.ini or in the script. I suspect it's not finding (or there is an error in) the validate_name() function and this is causing a fatal error. You can also check your error logs `/var/log/apache2/error.log` or equivalent on your system – Loopo Sep 22 '15 at 09:50
  • I dont know how to check logs or how to turn error reporting. I am sure that I may be doing some mistake in placing the code in submit.php file. May I request you to edit your submit.php code that you gave under the title "So your sumbit.php might look like:"? and remove the validation code that you gave under the title "In your submit.php you could then have"? I think I am not adding the code properly at a place where it should be. If you edit your code that you give along with the exact placement of validation code in the submit.php file, it will be of great help. Thanks – Sabha Sep 22 '15 at 11:07
  • I figured out why it was not working. There was a missing parenthesis in the if (!empty($_POST['name']){ line and the following line. Also instead of $error = true; it should have been $errors = true; missed the letter s. I want to ask one thing. When the errors are displayed in case it is not validated, it gives a link to try again but the data entered goes off. How can I get it back? – Sabha Sep 23 '15 at 18:15
  • sorry it was not parenthesis, it was closed bracket. Pls tell me what changes i must do to get the entered data back after clicking on "Try Again". It redirects to fresh index page and the data entered by user before clicking submit disappears. Something like the back browser button. Thanks a ton. – Sabha Sep 24 '15 at 05:56
  • you'll need to pass the data either as POST or GET parameters back to your index.php GET is simpler because you can add them to the url see my additional edit – Loopo Sep 24 '15 at 08:28
0

When you submit a form, the browser will jump the page which is specified in the target attribute of the form tag, in your case it's submit.php.

  1. After processing the POST data, your submit page should render something, which redirects back to index.html, alternatives:

  2. If you don't want to reload the page, you should use AJAX to send data to the server:

    • you should set up a listener on the submit button,
    • send the data upon pressing it,
    • also you should disable default action (which is jumping to target page).

First you should try the first one, it's easier.

ern0
  • 3,074
  • 25
  • 40
  • Thank you for the references. I will read it in a while. The second options looks a bit difficult for a novice like me LOL – Sabha Sep 15 '15 at 13:24
0

index.html

<form method="post" action="submit.php">
    //Html Codes
</form>

submit.php

<?php
$con = mysql_connect("localhost","myuser","mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);

$sql="INSERT INTO members (sName, sCity, sMobile, sEmail, sSub, sSlogan)
VALUES ('$_POST[name]', '$_POST[city]', '$_POST[mobile]', '$_POST[email]', '$_POST[sub]', '$_POST[slogan]')";
if (!mysql_query($sql,$con))
{
    die('Error: ' . mysql_error());
}
else
{
    header("location:index.html?Message=Success")
}
?>
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
  • Thank you for your reply. I tried this but the data does not go in the database. it just shows a blank submit.php page. – Sabha Sep 15 '15 at 13:18