0

I have two HTML pages, each has a form.
The user is supposed to fill out the input fields in one, then click a submit button that will send him to the next page, where he would fill out the rest of the fields of his questionaire, click a submit button.
After that I need all the input data collected from both pages (forms) to be inserted into one record in the database.
How would I achieve that?

Thanks a million in advance!

Edited by levsha: n/a

5
Contributors
14
Replies
15
Views
8 Years
Discussion Span
Last Post by levsha
Featured Replies
  • 1

    You can do it in 2 simple ways (maybe there are even more, but I am not aware of it). You can either save the data of the first form in session after it is posted, and then, when the second form is posted, get all the data (session data … Read More

  • 1
    diafol 3,720   8 Years Ago

    [QUOTE=levsha;1054527]I've never worked with Ajax at all. Could you please tell me more about this method or maybe point me to some article that explains it? Thank you![/QUOTE] Oh boy, where do I start? First of all, most of the time Ajax is pretty much javascript calling a php script … Read More

  • 2
    Atli 182   8 Years Ago

    [quote=ardav]The main stumbling block for most is the Ajax object. You can bypass all this nonsense with a javascript library called prototype.js.[/quote] Just to underline how much easier it is to work with libraries like Prototype and jQuery, this is how ardav's "doForm1" function would have looked like in native … Read More

1

You can do it in 2 simple ways (maybe there are even more, but I am not aware of it).
You can either save the data of the first form in session after it is posted, and then, when the second form is posted, get all the data (session data and the 2nd form's posted data) and insert a record to the table.
The second method is to have hidden fields in the 2nd form, which will save all the values of the first form and when the 2nd form is submitted, you will have the data of 1st and 2nd form :)

0

Hey.

You could use sessions to store the data from the first part of the form until the second one is submitted.

Or you could insert the data from the first page into the database as soon as it is submitted, have the user fill out the second part, and just update the row when the second part is submitted.

For example:

index.php

<form action="page2.php" method="post">
    <input type="text" name="first_info" />
    <input type="submit" />
</form>

page2.php

<?php
// Get the data from the last form
$first_info = mysql_real_escape_string($_POST['first_info']);
 
// Insert a new row into the database
$sql = "INSERT INTO tbl(first_info) VALUES('{$first_info}')";
mysql_query($sql) or trigger_error(mysql_error(), U_USER_ERROR);
 
// Get the ID of the row that was just created.
$row_id = mysql_insert_id();
?>
<form action="page3.php" method="post">
    <input type="hidden" name="row_id" value="<?php echo $row_id; ?>" />
    <input type="text" name="second_info" />
    <input type="submit" />
</form>

page3.php

<?php
// Get the data from the last form
$second_info = mysql_real_escape_string($_POST['second_info']);
$row_id = mysql_real_escape_string($_POST['row_id'])
 
// Update the row in the database with the new info
$sql = "UPDATE tbl 
        SET second_info='{$second_info}' 
        WHERE row_id={$row_id}
        LIMIT 1";
mysql_query($sql) or trigger_error(mysql_error(), U_USER_ERROR);
?>
<form action="page4.php" method="post">
    <input type="hidden" name="row_id" value="<?php echo $row_id; ?>" />
    <input type="text" name="third_info" />
    <input type="submit" />
</form>

etc...

0

Or you could insert the data from the first page into the database as soon as it is submitted, have the user fill out the second part, and just update the row when the second part is submitted.

The only problem with this is , if a user loses his interest midway [ie., after submitting 1st form], there will be a obsolete record in the table. Or else, this is good.

0

The only problem with this is , if a user loses his interest midway [ie., after submitting 1st form], there will be a obsolete record in the table. Or else, this is good.

True, that might be a problem. Although I have never really found to much data to be a problem :)
It could even help you refine your process; being able to see if a lot of people are abandoning it mid way, and exactly where.

I would still consider this marginally better than storing it all in a session. Bloated sessions are never a good thing. It would even be preferable, in my opinion, to use a database as temporary storage for things like this, rather than the session.

And I would never really consider re-posting it all back into the HTML between pages. That's just... not right, somehow. I would much rather create one big form and have client-side code simulate a multi-page submission.

0
[B]$row_id = mysql_insert_id()[/B]

This is it!
Since I am a newbee to PHP, I just didn't know how I could identify the row.
But inserting data from the first page right away and then updating the record with data from the second page was my initial idea!

Thank you so much!

0

I've tried something else, but it didn't work.
I have an identity (auto-increment) field 'inventorid' in my table.
When data from the first form is submitted, the row is inserted into the table and a new inventorid value is generated.
I put this into my PHP on the submittion of the second page:

$sql = "UPDATE inventors SET invname='$invname'
WHERE inventorid='(SELECT max(inventorid) FROM inventors )'";

Somehow it doesn't work...

0

I've tried something else, but it didn't work.
I have an identity (auto-increment) field 'inventorid' in my table.
When data from the first form is submitted, the row is inserted into the table and a new inventorid value is generated.
I put this into my PHP on the submittion of the second page:

$sql = "UPDATE inventors SET invname='$invname'
WHERE inventorid='(SELECT max(inventorid) FROM inventors )'";

Somehow it doesn't work...

actually the previous way is better... you should retrieve the inventorid from mysql_insert_id() function immediately after the insertion and keep track of ti. I will tell you the reason.
Imagine a user fills in the 1st part of form and the data gets entered into the DB. Now, while he is busy with filling 2nd part another user logs in and fills the 1st part of form which increments the inventorid. Now when u r trying to update 1st user's record with max(inventorid) it will give u the id of 2nd user and update it.. after that second user will do the same and overwrite those entries. This way the 2nd part of 1st user gets lost..
got my point??

0

This is a situation where ajax could help. You really don't need to have two pages. You could have just the one with a DIV that is updated to show different forms. This means you could have a number of different steps without changing the page.

0

Yes, it makes perfect sense.
Thank you!

actually the previous way is better... you should retrieve the inventorid from mysql_insert_id() function immediately after the insertion and keep track of ti. I will tell you the reason.
Imagine a user fills in the 1st part of form and the data gets entered into the DB. Now, while he is busy with filling 2nd part another user logs in and fills the 1st part of form which increments the inventorid. Now when u r trying to update 1st user's record with max(inventorid) it will give u the id of 2nd user and update it.. after that second user will do the same and overwrite those entries. This way the 2nd part of 1st user gets lost..
got my point??

0

I've never worked with Ajax at all.
Could you please tell me more about this method or maybe point me to some article that explains it?

Thank you!

This is a situation where ajax could help. You really don't need to have two pages. You could have just the one with a DIV that is updated to show different forms. This means you could have a number of different steps without changing the page.

1

I've never worked with Ajax at all.
Could you please tell me more about this method or maybe point me to some article that explains it?

Thank you!

Oh boy, where do I start?
First of all, most of the time Ajax is pretty much javascript calling a php script in order to change the contents of a tag. There's heck of a lot more to it, but that's the bit that usually interests people.

The main stumbling block for most is the Ajax object. You can bypass all this nonsense with a javascript library called prototype.js. You can get this from prototypejs.org. I should point out that there are a number of other libraries you could use, including jQuery and Yahoo! I tend to use prototype due to its simplicity and lack of bloat.

Example implementation:

1. Download the file and place it in a folder (let's call it 'scripts')
2. Create a blank text file and save it as myajax.js into 'scripts'.
3. Put script references to these files in the head area of your page:

...(dtd)...
<html>
<head>
   <script src="/scripts/prototype.js"></script>
   <script src="/scripts/myajax.js"></script>
</head>
<body>
...other html...
<div id = "ajform" >
<form method="post" action="" onsubmit="doForm1();">   
...form contents...
</form>
</div>
...other html...
</body>
</html>

The "myajax.js" file:

function doForm1(){
        fname = $F('firstname');
        sname = $F('surname');
        email = $F('email');
        //do some validation
        //$F('..') is shorthand for the id of the form item - it gives the value
        //if it passes the validation, do this:
        var param = "action=form1&fn=" + fname + "&sn=" + sname + "&em=" + email;	
  	var url = "/includes/myajaxform1.php";
  	var oAjax = new Ajax.Updater('ajform', url,{method: 'post',parameters: param});
}

The "includes/myajaxform1.php" file:

<?php
switch($_POST['action']){
   case "form1":
      $fname = mysql_real_escape_string($_POST['fn']);
      $sname = mysql_real_escape_string($_POST['sn']);
      $email = mysql_real_escape_string($_POST['em']);
      //validate the form data again     
      //if ok - add to DB or whatever and echo the next form
      //anything you echo out here will be displayed in the DIV
      break;
...etc...
}
?>

I've simplified the code above to give you an idea of how it works. It could be further optimized, but would be very confusing. The Ajax.Updater is the killer prototype function here. It just updates the div with whatever you output from the php file.

Edited by diafol: n/a

2

The main stumbling block for most is the Ajax object. You can bypass all this nonsense with a javascript library called prototype.js.

Just to underline how much easier it is to work with libraries like Prototype and jQuery, this is how ardav's "doForm1" function would have looked like in native JavaScript:

function doForm1(){
    var fname = document.forms[0].firstname.value;
    var sname = document.forms[0].surname.value;
    var email = document.forms[0].email.value;

    var url = "/includes/myajaxform1.php";
    var param = "action=form1&fn=" + fname + "&sn=" + sname + "&em=" + email + "&";

    var ajaxObj = null;
    if(XMLHttpRequest) {
        ajaxObj = new XMLHttpRequest();
    }
    else {
        try {
            ajaxObj = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e) {
            alert('Browser does not support AJAX.');
        }
    }
    ajaxObj.onreadystatechange = function() {
        if(ajaxObj.readyState == 4 && ajaxObj.status == 200) {
            document.getElementById('ajform').innerHTML = ajaxObj.responseText;
        }
        else {
            document.getElementById('ajform').innerHTML = 'Request failed';
        }
    };
    ajaxObj.open("POST",url,true);
    ajaxObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajaxObj.send(param);

    return false;
}

Not pretty.

P.S.
While I'm at it, here is a jQuery version of that function as well. (My favorite library :-)

function doForm1(){
    var url = "/includes/myajaxform1.php";
    var params = {
        fn : $('#firstname').val(),
        sn : $('#sirname').val(),
        em : $('#email').val()
    }
    $.post(url, params, function(data){
        $('#ajform').html(data);
    }, 'text');

    return false;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.