...

View Full Version : inserting multipage form into mysql



LegionSmith
12-18-2008, 05:09 AM
Hi Everyone!

I'm hoping someone here can help me. I have a 5 page form with roughly 175
fields/checkboxes that I'm trying to get inserted into a mysql database.
My deadline on this whole project was only 3 days so I had to figure out a quick method of doing things. Rather than using sessions and/or standard php arrays I found a snippet of code that takes all $_POST data from a previous page and creates hidden fields in the next page. That works just fine for this project.
here's that bit of code:


<?php foreach ($_POST as $key => $val) {
echo '<input type="hidden" name="' . $key . '" value="'
. htmlentities($val, ENT_QUOTES) . '" />' . "\r\n";
}
?>

Ok, so this as I said is spread out through pages 2 through 5 and each page posts to the next page. Then page 5 posts to process.php which is supposed to take all the previous fields and insert into a database. But I can't get it to work. here's what I have in process.php


<?php include("../Connections/wtrcapp.php"); ?>
<?php foreach ($_POST as $key => $val) {
echo '<input type="hidden" name="' . $key . '" value="'
. htmlentities($val, ENT_QUOTES) . '" />' . "\r\n";
}
foreach($key as $val) {
$insert="INSERT INTO westoco6_app (".implode(",", array_keys($key)).") VALUES ('".implode("','", array_values($val))."')";
}
mysql_query($insert) OR die(mysql_error())
?>

Now I don't know that I'm even close to the mark on this but i think I am...most of my errors originate from line 6, the second foreach statement.
If anyone can give me a clue as to what I'm doing wrong here or point me in a better direction I'd be very appreciative. My deadline ends in the morning.

Thanks much for your time,
Michael Smith

masterofollies
12-18-2008, 05:20 AM
My best guess is this part


'".implode("','",

which is in the insert query. It may be using the single quote as an ending to the first insert value. Maybe it needs a slash in it?

LegionSmith
12-18-2008, 05:25 AM
so change this:

('".implode("','",

to this?

('/".implode("','",

LegionSmith
12-18-2008, 05:26 AM
I guess I should have mentioned the error I get is:


Warning: Invalid argument supplied for foreach() in /home/westoco6/public_html/app/process.php on line 6
Query was empty

PappaJohn
12-18-2008, 05:34 AM
foreach() requires an array which $key is not.

LegionSmith
12-18-2008, 05:41 AM
right, ok...I get that. the script that creates the hidden fields is creating an array is it not? I haven't used arrays much so I'm out of my comfort zone here.
I realize this method might not even be close to what I should be doing, but I assumed that I could foreach of the values from all the previous pages and implode into the db, all of this without manually typing 175 fields into an array.


Does that make sense? any clue as to what I should do here?
I'm pretty well stuck and a bit confused here.

Thanks much!
Michael

PappaJohn
12-18-2008, 05:54 AM
This line, pulls the values from the $_POST array:

<?php foreach ($_POST as $key => $val)

By the time you get to here:

foreach($key as $val)
The loop above has already run through all the variables in the $_POST array, and so $key is the name of the last variable the loop ran through. That is why it is not an array by the time you get to this line.

I don't know what the data looks like from your $_POST array, but you could well run into problem simply imploding them into the SQL statement due to not presenting the data to MySQL in the form it expects (ie: missing quotes around string variables, etc). I guess if you're careful with your data, you could make it work.

Additionally, simply imploding the data into your SQL statement is not providing any security. Since the $_POST array comes from the browser, the data contained in it can be altered by the user, regardless of whether it is in hidden fields or not. Therefore, it cannot be trusted, and you should be using mysql_real_escape_string().

LegionSmith
12-18-2008, 06:16 AM
Ok I understand what you're saying about it not being an array anymore...I see your point there.
I also get the issue with imploding, I'm just using code provided at a snippet site, none of this really isn't my strong suit.
Supposedly all the code I had would do exactly what I needed it to do, but obviously it didn't.
I'm just trying to find a viable solution to inserting all those fields into mysql without manually typing everything, as I said before. There just wasn't time for all of that.

Regarding security of the data, it's really not an issue as it's on an intranet and apparently is going to be totally revamped in phase 2 anyway. So I'm not worried about escaping characters for now. This is just how they want it for now (like the next 2 weeks) and after that it's just going straight to pdf. But that will never happen if I don't get this part down first.

Do you have any suggestions as to what I should actually be doing with this processing script? Is there another way of accomplishing this without the implode?

This is my latest iteration of the code, having added the $array variable and changing the foreach, but this just returns even more errors.


<?php include("../Connections/wtrcapp.php"); ?>
<?php foreach ($_POST as $key => $val) {
echo '<input type="hidden" name="' . $key . '" value="'
. htmlentities($val, ENT_QUOTES) . '" />' . "\r\n";
}
$array = array('$key','$val');
foreach ($array as $insert) {
$insert="INSERT INTO application (".implode(",", array_keys($key)).") VALUES ('".implode("','", array_values($val))."')";
}
mysql_query($insert) OR die(mysql_error())
?>

I get the feeling that I'm going about the process.php page totally wrong, but again this out way out of my realm.

Thanks very much for the help you've been giving.

Michael

PappaJohn
12-18-2008, 06:27 AM
OK, your getting closer.

Remove this line:

$array = array('$key','$val');
For the reasons I explained above, by the time you get to this line, $key & $val only contain the values from the last iteration of the loop above.

However, all of the $_POST variables are still intact.

So, change:


foreach ($array as $insert) {
$insert="INSERT INTO application (".implode(",", array_keys($key)).") VALUES ('".implode("','", array_values($val))."')";
}

to


foreach ($_POST as $key => $val) {
$insert="INSERT INTO application (".implode(",", array_keys($key)).") VALUES ('".implode("','", array_values($val))."')";
}

I can't be certain without seeing the form and incoming data if this will succeed or not.

If it does not succeed. Add this line immediately after mysql_query($insert) OR die(mysql_error());


echo $insert . '<br>';

LegionSmith
12-18-2008, 06:40 AM
Ok cool, I see where you're going with this. all the $_POST is still in memory so I just need to access the $_POST at this point, not necessarily the array. I'm confused by all the implode and array_keys though. That's what I get for using code I don't understand i guess.

Anyway, I tried what you just said and I got a whole slew of errors on line 8. you can see it here: http://westtexasrehab.org/app/process.php
You can just go to /app to see the start of the form. There's only validation
on the first part of page one. After that nothing is necessarily required.

I also tried the echo statement and that returned an error on line 11...the echo lline.

Since we're now just using $_POST, are the array keys and implode
still necessary? Does $_POST save all of the information or just the last submitted?

I know all of this seems silly as it's going to be revamped anyway...the form
used to work in a completely different manner, then the server got hacked
and all the pages were totally jacked up. They gave me 3 days to build the original form again but stated that they'd want to go a totally different route.
they also said they didn't care about security whatsoever this time around. Whatever, I just do as I'm asked.

That last bit of help was awesome, thank you so much for that.
Michael

PappaJohn
12-18-2008, 06:48 AM
Well, some of that was my bad, I honestly never looked past the foreach issue.

Let's try a new query


$insert="INSERT INTO application (".implode(",", array_keys($_POST)).") VALUES ('".implode("','", array_values($_POST))."')";

This is assuming that the field names in your database, match the input field names from $_POST. If not, this will not work. Assuming they do ...

You don't need the foreach here at all, because you're using array_keys() and array_values().

array_keys() returns the keys from an array, and array_values() returns the values. So, imploding array_keys() will set the field names and imploding array_values() will set the values to be inserted in the fields.

So, replace:


foreach ($_POST as $key => $val) {
$insert="INSERT INTO application (".implode(",", array_keys($key)).") VALUES ('".implode("','", array_values($val))."')";
}

with


$insert="INSERT INTO application (".implode(",", array_keys($_POST)).") VALUES ('".implode("','", array_values($_POST))."')";


Again, if it fails with no errors, echo $insert to see what it contains.


Q. Does $_POST save all of the information or just the last submitted?

A. Only the last submitted. When this script terminates, $_POST will be cleared.

LegionSmith
12-18-2008, 06:52 AM
On a side note, this is where I found the "pass form fields in a multi page form" snippet:
http://www.earn-web-cash.com/2008/02/08/multi-page-form-revisted/

LegionSmith
12-18-2008, 07:00 AM
Ok, that's looking much better. Now I'm just getting a "No Database selected" error. which is weird. I've got navicat running and double checked everything in my connection script, not sure whats going on there.

when I try to echo to see what values it's getting I get the error:
Parse error: syntax error, unexpected T_ECHO in /home/westoco6/public_html/app/process.php on line 9

Let me see if I can figure out why it's giving the no database error, but I'm really hopeful that you may have got it figured out.

Michael

PappaJohn
12-18-2008, 07:05 AM
Hmm, that's a little harder to say from here. I'm assuming this line

<?php include("../Connections/wtrcapp.php"); ?>
includes the db connection code.

It should include a mysql_connect() statement with the proper parameters and a mysql_select_db() statement. Make sure each of these includes an or die(mysql_error()).

You can post the contents of the file if you'd like, but first, be sure to edit out any sensitive info.


Parse error: syntax error, unexpected T_ECHO in /home/westoco6/public_html/app/process.php on line 9
Post the code on a few lines surrounding line 9, although it could well be a missing semi-colon ; .

LegionSmith
12-18-2008, 07:18 AM
yeah, it's obviously the connection script. I've been double checking it and it looks good to me. here it is minus the sensitive info:


<?php
# Type="MYSQL"
# HTTP="true"
$hostname_wtrcapp = "myhost";
$database_wtrcapp = "mydb";
$username_wtrcapp = "myusername";
$password_wtrcapp = "mypass";
$wtrcapp = mysql_pconnect($hostname_wtrcapp, $username_wtrcapp, $password_wtrcapp) or trigger_error(mysql_error(),E_USER_ERROR);
?>

Now I just noticed that my connection has mysql_pconnect and my process.php script is using mysql_query. I tried changing the process to mysql_pconnect and I get this error:

Warning: mysql_pconnect() [function.mysql-pconnect]: Unknown MySQL server host 'INSERT INTO application (Position,date_mm,date_dd,date_yy,Relative,Other,Last_Name,First_Name,Middle' (3) in /home/westoco6/public_html/app/process.php on line 8

arrghh this is so frustrating. I think you've got it, I checked the source and all the fields are there, I think they'd submit if it could find the db. I don't understand why it's not, I've used this same connection script in the past and it's always worked.

I also did change line 1 of process.php to

<?php require_once('../Connections/wtrcapp.php'); ?>
instead of include.

Thank you so much for all the help you've been giving, I owe you a beer for sure.

Michael

PappaJohn
12-18-2008, 07:25 AM
I would advise against the use of MySQL persistent connections unless you know what you're doing with them. They usually aren't necessary, this case included.

1. Change the mysql_pconnect() to mysql_connect(), the arguments are the same.
2. I don't see a mysql_select_db() statement anywhere in the code you've posted. Establishing a connection to a specific database is a two-step process.

a. Execute mysql_connect() to establish a connection to MySQL.
b. Execute mysql_select_db() to specify the database you want to work with. You could have multiple databases.

You'll likely have more debugging to do, but the first step is to successfully connect to your database.

LegionSmith
12-18-2008, 07:43 AM
Ok, If you're still there, I've just about got it. I fixed the connection, and it's trying to insert into the db. My only problem now is that it's trying to insert the submit button into the database as well. I know there's a way to omit that value but I can't remember how...nor can I find anything via google....any ideas?

Thanks,
Michael

addendum: yeah I changed the persistent and for the time being inserted my connection straight into process.php

mysql_connect("localhost", "myuser", "mypass") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());

again, it's working now but I get this error:
Unknown column 'submit' in 'field list'
I see the submit value in the source...it's from the application submit on page 5. so if we can just omit trying to enter that value somehow we'd have it.

PappaJohn
12-18-2008, 07:56 AM
Well, since this is an internal-use, short lifespan app, we can take a quick and dirty approach.

Change:


$insert="INSERT INTO application (".implode(",", array_keys($_POST)).") VALUES ('".implode("','", array_values($_POST))."')";


To:


$input = array();
foreach ($_POST as $key => $val)
{
if ($val != 'submit') $input[$key] = $val;
}

$insert="INSERT INTO application (".implode(",", array_keys($input)).") VALUES ('".implode("','", array_values($input))."')";



Updated this post to a better solution

LegionSmith
12-18-2008, 08:02 AM
yeah! I knew there was a way to do that.
unfortunately after adding that:


foreach ($_POST as $key => $val) {
echo '<input type="hidden" name="' . $key . '" value="'
. htmlentities($val, ENT_QUOTES) . '" />' . "\r\n";
}
$submit_btn = array_keys($_POST, 'submit');
array_splice($_POST, $submit_btn, 1, "");
$insert="INSERT INTO application (".implode(",", array_keys($_POST)).") VALUES ('".implode("','", array_values($_POST))."')";
mysql_query($insert) OR die(mysql_error())
?>

I now get the error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0,date_mm,date_dd,date_yy,Relative,Other,Last_Name,First_Name,Middle_Name,Addres' at line 1

Obviously I have a deeper issue somewhere.

I'm going to have to go to bed now, getting late here. I'll play with it some more tomorrow. I'm supposed to have it working by then but I don't think that's going to happen.

Let me know what you think on this latest error, and if you ever need anything just let me know. You've been an IMMENSE help tonight. I really, really appreciate it.

Thanks again,
Michael Smith

PappaJohn
12-18-2008, 08:10 AM
This is where echoing the SQL statement comes in handy - it'll show you exactly what's in the query.

Just add this:


$insert="INSERT INTO application (".implode(",", array_keys($_POST)).") VALUES ('".implode("','", array_values($_POST))."')";
echo $insert . '<br>';
mysql_query($insert) OR die(mysql_error());

I realize a terminating semicolon on the last line is optional, but IMO it's a good idea to get in the habit of terminating ALL statements with semicolons.

LegionSmith
12-18-2008, 04:00 PM
yeah ok, I did the echo. this is what it returns:


INSERT INTO application (0,date_mm,date_dd,date_yy,Relative,Other,Last_Name,First_Name,Middle_Name,Address,Number,Street,Cit y,State,Zip,telephone,Time_1,Time_2,Time_4,Eligibility_1,previous_app_1,previous_app_3,previous_empl oy_1,previous_employ_3,relatives_1,currently_employed_1,contact_employer_2,immigration_1,date_availa ble_1,date_available_2,date_available_3,salary_range,full_time,shift,part_time,part_time_shift,temp_ dates_1,temp_dates_2,temp_dates_3,temp_dates_4,temp_dates_5,temp_dates_6,layoff_status_1,travel_1,su bmit,Elem_Name,Elem_Study,Elem_Years,Elem_Diploma,High_School_Name,High_School_Study,High_School_Yea rs,High_School_Diploma,Undergrad_Name,Undergrad_Study,Undergrad_Years,Undergrad_Diploma,Graduate_Nam e,Graduate_Study,Graduate_Years,Graduate_Diploma,Other_Name,Other_Study,Other_Years,Other_Diploma,sp ecialized_training,military_training,Employer1,Employer1_address,Employer1_telephone,Employer1_Job_T itle,Employer1_Supervisor,Employer1_Reason_For_Leaving,Employer1_Dates_Employed_1,Employer1_Dates_Em ployed_2,Employer1_Dates_Employed_3,Employer1_Dates_Employed_4,Employer1_Dates_Employed_5,Employer1_ Dates_Employed_6,Employer1_Salary_Starting,Employer1_Salary_Final,Employer1_Work_Performed,Employer2 ,Employer2_address,Employer2_telephone,Employer2_Job_Title,Employer2_Supervisor,Employer2_Reason_For _Leaving,Employer2_Dates_Employed_1,Employer2_Dates_Employed_2,Employer2_Dates_Employed_3,Employer2_ Dates_Employed_4,Employer2_Dates_Employed_5,Employer2_Dates_Employed_6,Employer2_Salary_Starting,Emp loyer2_Salary_Final,Employer2_Work_Performed,Employer3,Employer3_address,Employer3_telephone,Employe r3_Job_Title,Employer3_Supervisor,Employer3_Reason_For_Leaving,Employer3_Dates_Employed_1,Employer3_ Dates_Employed_2,Employer3_Dates_Employed_3,Employer3_Dates_Employed_4,Employer3_Dates_Employed_5,Em ployer3_Dates_Employed_6,Employer3_Salary_Starting,Employer3_Salary_Final,Employer3_Work_Performed,E mployer4,Employer4_address,Employer4_telephone,Employer4_Job_Title,Employer4_Supervisor,Employer4_Re ason_For_Leaving,Employer4_Dates_Employed_1,Employer4_Dates_Employed_2,Employer4_Dates_Employed_3,Em ployer4_Dates_Employed_4,Employer4_Dates_Employed_5,Employer4_Dates_Employed_6,Employer4_Salary_Star ting,Employer4_Salary_Final,Employer4_Work_Performed,Other_Activities,Other_Qualifications,Terminal_ Skills,Spreadsheet_Skills,Typewriter_WPM,Shorthand_WPM,Production_Machinery_Skills,Other_Skills,Othe r_Helpful_Info,Essential_Functions_Yes,References1_Name,References1_Phone,References1_Address,Refere nces2_Name,References2_Phone,References2_Address,References3_Name,References3_Phone,References3_Addr ess,Applicant_Signature,Signature_Date) VALUES ('','23','13','1423','yes','','fgdfgf','bgfhbnhm','jmmjhmjm','jmjhmj','mfgdsf','sdfdfg','fgfdgdfg',' gfdbfdgb','432432','gdsfg43324','43','34','AM','yes','yes','','yes','','yes','yes','no','yes','34',' 34','34','234324','yes','1','yes','Mornings','','','','','','','yes','yes','Submit my Application','4rerefdf','dfvdbfb','fgfgbbg','','bgfbgfbg','ngngng','nghnn','','ngnfgn','nngh','nn',' ','nhnghn','ghnhn','2344rewrwer','','','','','','23tcvdvre','dfvcvtgte5r4','gvfdbvdvbf','et4t','egde 324423','4324fdf','wfdf4','34ffsdef','32','34','34','34','42','42','24234','53543345rt','dfbfdhbthbt ','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','' ,'','','','','','','','','','','','','ngbvn hgnrt6hy','hbvnfygnbr','yes','yes','45','324','gbdfbfbfgbfgbgf','bgbffbvb','fbbgbvgbngf','yes','fvbn gfnb','fdggnfnb','gbnvn','gfbn','bfbg','fbgfgb','bfb','gfbgf','gfbfgb','rthhfgbhf','g34234')
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0,date_mm,date_dd,date_yy,Relative,Other,Last_Name,First_Name,Middle_Name,Addres' at line 1

so it looks to me like it's trying to insert not only the values but the input names as well. also that first zero would be the auto increment id input..

maybe this was totally the wrong way to go about passing the fields?

Michael

LegionSmith
12-18-2008, 08:55 PM
Actually, I just got it working.

For future viewers of this post, here is all the working code I used for passing form values through several pages and then finally posting into a database after completion of form:

Use this code in all form pages except your first form page:


<?php foreach ($_POST as $key => $val) {
echo '<input type="hidden" name="' . $key . '" value="'
. htmlentities($val, ENT_QUOTES) . '" />' . "\r\n";
}
?>

place the code above just inside your form begin tag. example:

<form method="POST" action="employment3.php" enctype="application/x-www-form-urlencoded" name="employment_form" id="employment_form">
<?php foreach ($_POST as $key => $val) {
echo '<input type="hidden" name="' . $key . '" value="'
. htmlentities($val, ENT_QUOTES) . '" />' . "\r\n";
}
?>

Then in your final processing script use the code below. change the database values to match your own:

<?php
mysql_connect("myhost", "myusername", "mypass") or die(mysql_error());
mysql_select_db("mydatabase") or die(mysql_error());

if(!empty($_POST))
{

$first="";
$second="";
$insert="INSERT INTO mydbtable (";
foreach ($_POST as $key => $var)
{
if($key!="submit")
{
$first.=$key.","; // <----- use ` in field names if you want to make this better
$second.="'". mysql_real_escape_string($var)."',"; // <----- use ' on values.

echo '<input type="hidden" name="' . $key . '" value="' . htmlentities($var, ENT_QUOTES) . '" />' . "\r\n";
}
}
$query=$insert.$first.") VALUES (".$second.");";
$query=str_replace(",)",")", $query) ;
mysql_query($query) OR die(mysql_error()) ;
}
?>

And that's exactly what worked for me. it would be best to separate the connection in an include file, and you'll probably also need to redirect to a success page in this script...but the above will allow you to pass form values somewhat securely between several pages and insert them into mysql at the end of all things.
The purpose of this was to pass values without having to manually create sessions or variables for each and every form value. Quite handy for long forms such as mine. Note that the values will be visible in the source code of every page. But, it's a quick and dirty way to get the job done.

Special thanks goes to "icandothat", PappaJohn" and "djjjozsi" for helping me figure this out.

Thanks much!

Michael Smith



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum