Question

I have database structure like this

database structure

Now i have designed form to enter Fm and PM for different subject

entry form

Now how can I insert values from the above form in this database as multiple rows to be inserted at once

Was it helpful?

Solution 2

As i can see you have taken fm and pm but you need to have array type here find below code to get it understood

 <?php 
include_once('dbconfig.php'); 
$mysql="Select * from subjects where class_id='$class_id' "; 
$result=mysql_query($mysql); ?>

<form method='post' action='insert.php'>
  <?php  
while($row=mysql_fetch_array($result)) { 
    echo $row['subject_name']; 
?>
  <input type='text' name='fm[]' placeholder='fullmarks' class='input-small'>
  <input type='text' name='pm[]' placeholder='passmarks' class='input-small'>
  <br/>
  <?php } ?>
  <button id='classbutton' name='submit' class='btn btn-success'> Save</button>
</form>

and insert.php you can use Like this

for($i = 0; $i <count($_POST)-1; $i++)
{
    mysql_query("INSERT INTO `marks`(`fm`,`pm`) VALUES('".$_POST['fm'][$i]."','".$_POST['pm'][$i]."');");
}

Here marks as a table name and fm,pm are table colume

OTHER TIPS

You can insert multiple rows at once using the following syntax:

INSERT INTO tablename (column1, column2)
VALUES (val1, val2),
(val1, val2);

Yours would resemble (with you probably wanting to add additional columns):

INSERT INTO tablename (fm, pm)
VALUES (100, 40),
(100, 60);

See MySQL INSERT Syntax

in the form use an array like marks[subject_id] the subject div can be repeated for all the subjects

<form action="insert.php">

<div class="subject">
<input type="text" name="marks[1][fm]">
<input type="text" name="marks[1][pm]">
</div>

<input type="submit">

Then in insert.php loop through _POST['marks'] and foreach construct an INSERT statement and insert this row.

i don't know if you have actual backend in place, make sure you escape the inputs to avoid sql injection, here you'll find one way to do it

http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top