Forum Moderators: coopster
$query = "insert into items values
('".$q1."', '".$q2."', '".$q3."', '".$q4."', '".$q5."','".$q6."', '".$q7."', '".$q8."', '".$q9."', '".$q10."')";
The problem is, I will eventually need 300 questions so I don't want to list them all individually. How can change this snippet of code so that it says something along the lines of "please insert all the variables q1-q300 into the database"?
Ed
Something like --
for($x = 0; $x < 300; $x++){
$item = $q[$x];
$query = "INSERT INTO items VALUES ($item)";
mysql_query($query);
}
of course, I'm not sure what your database table is like, and theres no error catching there either, hope that helps.
PHP Arrays - www.php.net/array
foreach ($_POST as $key => $val){
if ($key{0} == "q") mysql_query("insert into...");
}
just finish off the insert and use the variable $val for the value.
The if ($key{0} == "q") part is there to only insert fields that start with "q". Otherwise all form field values will be inserted. Even "Submit".
for($x = 0; $x < 10; $x++){
$item = $q[$x];
$query = "INSERT INTO items VALUES ($item)";
mysql_query($query);
}
It inserted ten sets of data into my table, as if ten people had answered the questions rather than one. Am I doing something wrong?
Could you explain what ($x = 0; $x < 10; $x++) means? Is it saying, "for all questions between zero and 10" or something else?
Many thanks
Does your database just have one row for each set of questions? (I guess that would mean your table would have to have ~300 columns.) If that is the case, perhaps something like this could work:
$query = "INSERT INTO items VALUES (";
for($x = 0; $x < 9; $x++){
$item = $q[$x];
$query .= $item . ",";
}
// I just put the last item in here, to fix commas
$item = $q[9];
$query .= $item . ")";
mysql_query($query);
This will generate one big insert rather than 10 short ones.