Jump to content

Insert into database through a loop or array?


razorlegacy

Recommended Posts

I have a problem where I want to get these variables and insert them into a database.

 

I know how to insert one entry at a time but I want to insert 50 of these from one submit. How can I make multiple inserts in a loop?

<form id="insert" name="insert" method="post" action="http://www.mikeonlinetests.com/admin/questions.php">
Select a Test <select name="test_id">
<?
$sql = mysql_query("SELECT * FROM tests ORDER BY version ASC");
$tests = array();
while ($test = mysql_fetch_assoc($sql)) {
$tests[] = sprintf("<option value=\"%s\">%s->%s-%s</option>\n", 
$test['test_id'], $test['version'], $test['date_m'], $test['date_y']); } echo '' . join('' , $tests);
?>
</select>
<table width="100%" border="0" cellspacing="0" cellpadding="4">
<? $y = 1; while($y < 51) { ?>
<tr>
<td width="10" align="right" valign="top"><b><?php echo $y; ?>)</b></td>
<td>Questions<br/>
<textarea name="question" cols="60" rows="2"></textarea><br/>
Image<br/>
<input name="img" type="text" size="40" maxlength="50"/><br/><br/>
Answers<br/>
<? $a = 1; while($a < 6) { ?>
<b><?php echo $a; ?>)</b> <input name="c_a" type="radio" value="<?= $a; ?>"/> <textarea name="a<?= $a; ?>" cols="25" rows="2"></textarea>
<br/>
<? $a++; } ?><br/>
</td></tr>
<? $y++; } ?>
</table>
</form>

This is my insert code

<?
$test_id = check_input($_POST['test_id']);
$question = check_input($_POST['question']);
if(!empty($_POST['img'])){ $img = check_input($_POST['img']); }else{ $img = "NULL"; }
$a1 = check_input($_POST['a1']);
$a2 = check_input($_POST['a2']);
$a3 = check_input($_POST['a3']);
$a4 = check_input($_POST['a4']);
$a5 = check_input($_POST['a5']);
$c_a = check_input($_POST['c_a']);
if(!empty($_POST['c_a_img'])){ $img = check_input($_POST['c_a_img']); }else{ $img = "NULL"; }

$sql = @mysql_query("INSERT INTO `questions` (`qid`, `test_id`, `question`, `img`, `a1`, `a2`, `a3`, `a4`, `a5`, `c_a`, `c_a_img`) VALUES (NULL, '$test_id', '$question', '$img', '$a1', '$a2', '$a3', '$a4', '$a5', '$c_a', '$c_a_img')");
if(!$sql){
      echo "Error inserting your information into MySQL: ".mysql_error();
      footer();
      exit();
}
?>

 

Thanks

Hi,

 

If you know the amount of times that you need to enter the data into the database, you could use a loop in your insert code as follows:

 

<?php 
$i=1;
while($i<=5)
  {
  // Insert query goes here
  $i++;
  }
?>

 

This snippet is courtesy of w3schools and not my own.

Hope it can help you.

 

Regards,

Iceman

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.