I will show how I would do this, trying to make a walkthough:
Change the field names to machine[][dap]
and machine[][tractor]
.
Using machine[]
will create an array, with each field name inside []
.
Create a new array, called (for example) $sql
, like this:
$sql=array();
Cycle though each $_POST
using foreach
:
foreach($_POST['machine'] as $v)
Inside the foreach
, you will assign the 'built' query piece to $sql
:
$sql[]='"'.my_escape($v['dap']).'","'.my_escape($v['tractor']).'"';
notice: my_escape
is a fictional function, used to escape the data (like mysql_real_escape_string()
).
Run your query, and join the array with it:
$connection->query('insert into machinery (tractor_hiring,water_pump)VALUES('.implode('),(',$sql).')');
Final code (file 1):
<form name="" action="" method="post">
<p>Write Down How many rows are you trying to insert<input type="text" name="numb" placeholder=""/></p>
<input type="submit" name="add"/><br>
<?php
if(isset($_REQUEST['add'])){
$add=$_POST['numb'];
for($i=0; $i<$add; $i++) {
echo "<form method=\"post\" action=\"2.php\" >";
echo "Water Pump<input type=\"text\" name=\"machine[][dap]\"/><br>
Tractor Hiring<input type=\"text\" name=\"machine[][tractor]\"/><br><form>";
} echo "<input type=\"submit\" name=\"save\"/><br>";
}
?>
Final code (file 2):
<?php
if(isset($_REQUEST['save'])){
$sql=array();
foreach($_POST['machine'] as $v)
{
$sql[]='"'.my_escape($v['tractor']).'","'.my_escape($v['dap']).'"';
}
$connection->query('insert into machinery (tractor_hiring,water_pump)VALUES('.implode('),(',$sql).')');
if($insert!=true)
echo "nothing happens";
else
echo "good to go";
}
?>
NOTICE: I AVOIDED TO TOUCH THE CODE INDENTATION (changed only on the 2nd file, cause it was terrible). YOU should indent EVERY FILE in a proper way!
Also notice that I used the same fictional function on the final code.
For the reported problem about the 1st page, here are the changes:
The form has no action. Easily fixed by setting action="#"
.
Only inputs with a value will be sent. <input type="submit" name="add"/>
doesn't have a value.
<input type="submit" name="add" value="Add"/>
Notice: the value
will also be used as the text to be displayed.
You don't have a closing </form>
for the main <form>
.
Final result:
<form action="#" method="post">
<p>Write Down How many rows are you trying to insert<input type="text" name="numb" placeholder=""/></p>
<input type="submit" name="add" value="Add"/><br>
</form>
<?php
if(isset($_REQUEST['add'])){
$add=$_POST['numb'];
for($i=0; $i<$add; $i++) {
echo "<form method=\"post\" action=\"2.php\" >";
echo "Water Pump<input type=\"text\" name=\"machine[][dap]\"/><br>
Tractor Hiring<input type=\"text\" name=\"machine[][tractor]\"/><br><form>";
} echo "<input type=\"submit\" name=\"save\"/><br>";
}
?>