I'm using MySQL query to insert multiple records into table.
In my url i get all records that i have entered but in database it only updates my last record. I am using here onclick function to add new table rows. Any help.
Here is my code
if (isset($_GET['submit']))
{
require_once("shine_class.php");
$s = new shine;
$s->connection();
$date1 = date_default_timezone_set('Asia/Kolkata');
$date1= time() ;
$newdate1 = date("d-m-Y", $date1);
for ($i=0; $i < count($_GET['finished_product_name']); $i++ )
{
$product =$_GET['finished_product_name'];
$material = $_GET['material_name'];
$quantity = $_GET['product_quantity'];
// mysql_query("INSERT INTO material_used (product_name, material_name, product_quantity, date) VALUES ('$a', '$b', '$c','$newdate1')") or die(mysql_error());
$insert ="insert into material_used set `product_name` = '".$product."', `material_name` = '".$material."', `product_quantity` = '".$quantity."',`date` = '".$newdate1."' ";
$select = mysql_query($insert) or die(mysql_error());
}
}
You try to assign a value with same name.so your last value replace with the existing value.
for example :your URL look like,
http://www.example.com/index.php?finished_product_name=abc&material_name=xxx&finished_product_name=pqr&material_name=yyy
so your $_GET['finished_product_name']
has value is pqr
not abc
.
If you can change the field name with include []
, then PHP will create an array containing all of the matching values:
http://www.example.com/index.php?id[]=123&version[]=3&id[]=234&version[]=4
your URL example like,
http://www.example.com/index.php?finished_product_name[]=abc&material_name[]=xxx&finished_product_name[]=pqr&material_name[]=yyy
your for loop is :
for ($i=0; $i < count($_POST['finished_product_name']); $i++ )
{
$product =$_POST['finished_product_name'][$i];
$material = $_POST['material_name'][$i];
$quantity = $_POST'product_quantity'][$i];
}
$insert ="insert into material_used(product_name,material_name,product_quantity,date) VALUES( '$product', '$material','.$quantiy','$newdate1')
use following function to insert data in DB
$data['col1']='value1';
$data['col2']='value2';
.
.
$data['coln']='valuen';
insert('table_name',$data);
function Insert( $table, $condition )
{
$sql = "INSERT INTO `$table` SET ";
$content = null;
foreach ( $condition as $k => $v )
{
$v_str = null;
if ( is_numeric($v) )
$v_str = "'{$v}'";
else if ( is_null($v) )
$v_str = 'NULL';
else
$v_str = "'" . mysql_real_escape_string($v) . "'";
$content .= "`$k`=$v_str,";
}
$content = trim($content, ',');
$sql .= $content;
return $result = mysql_query($sql);
}