Forum Moderators: coopster
I got the general idea for my script from this thread:
[webmasterworld.com...]
I have one form submitting a dynamic amount of identical entries depending on how many are generated from the query for the specific date. Each form "set" consists of four values, qid#, a#, a#, a#. So for example, three sets of these equal forms will create the following values:
qid1, a1, a2, a3
qid2, a4, a5, a6
qid3, a7, a8, a9
....
etc
I would like to insert each of these "sets" of values as a new row in my table. Right now I'm using the following code and I'm having problems:
$a=0;
$sql = "insert into answers (qid,a1,a2,a3) VALUES( ";
foreach ($_POST as $key => $val)
{
if ($a==0) $sql .= " ' " . $val . " ', ";
if ($a==1) $sql .= " ' " . $val . " ', ";
if ($a==2) $sql .= " ' " . $val . " ', ";
if ($a==3)
{
$sql .= "'" . $val . "'" . ")";
echo "<br>$sql<br>";
$result = mysql_query($sql);
} // endIF a = 6
if($a==3)
{
$a=0;
}
else
{
$a ++;
}
} // endFOREACH
However, when I do a echo of the $sql I get the following output:
insert into answers (qid,a1,a2,a3) VALUES( ' 1 ', ' 1 ', ' 4 ', '2')
insert into answers (qid,a1,a2,a3) VALUES( ' 1 ', ' 1 ', ' 4 ', '2') ' 2 ', ' 1 ', ' 5 ', '3')
The output of the following code is:
foreach ($_POST as $key => $val)
{
echo "<br>$key $val";
}
qid1 1
a1 1
a2 4
a3 2
qid2 2
a4 1
a5 5
a6 3
submit Submit
So I know the proper values are being passed.
The first query is fine, the second query just starts over and adds the second set to the end. It's using the proper values for the second set but not setup correctly.What am I doing wrong? I have a feeling its someone where in the loops.
Then when you process:
foreach($_POST['qid'] as $idx => $val) {
$qid = $val;
$a1 = $_POST['a1'][$idx];
$a2 = $_POST['a2'][$idx];
$a3 = $_POST['a3'][$idx];
$sql = "insert into answers (qid,a1,a2,a3) values ('$qid','$a1','$a2','$a3')";
$result = mysql_query($sql);
} // EndForEach segment
If you really, really want to do it the way you laid it out, then you could do this:
$sql_proto = "insert into answers (qid,a1,a2,a3) values (";
$sql = '';
$count = 0;
foreach($_POST as $key => $val) {
if($count%4) {
$sql .= "'$val',";
} // EndIf this is an a#
else {
if($sql!= '') {
$sql = substr($sql,0,-1) . ")";
$result = mysql_query($sql);
} // EndIf this isn't first time through
$sql = $sql_proto . "'$val',"
} // EndElse this is a qid
$count++;
} // EndForEach posted value