Mysql : Table multiple rows Insert into one sql row - php

Currently I'm creating a software, where i can create multiple row in a table.
But the why I wrote PHP code, it create multiple rows into SQL but i need to create one row against one invoice number.
Html (auto generate using ajax):
<tr>
<td><input class="form-control" type="text" name="product_name[]" value="'.$proData['name'].'"></td>
<td><input class="form-control qnt'.$proData['id'].'" min="0" step="any" type="number" name="qnt[]" placeholder="Quantity"></td>
<td><input class="form-control unit_price'.$proData['id'].'" type="number" min="0" step="any" name="unit_price[]" placeholder="Unit Price"></td>
<td><input class="form-control pack_size'.$proData['id'].'" type="number" min="0" step="any" name="pack_size[]" placeholder="Pack Size"></td>
<td><input class="form-control unit_pack'.$proData['id'].'" type="number" min="0" step="any" name="unit_pack[]" placeholder="Unit Pack (jar/Drum)"></td>
<td><input class="form-control total_kg'.$proData['id'].'" type="number" name="total_kg[]" placeholder="Total Kg/s" value="" readonly></td>
<td><input class="form-control total_price'.$proData['id'].'" type="number" name="total_price[]" placeholder="Total Price ৳" value="" readonly></td>
<td><button type="button" class="rowDelete btn btn-danger"><i class="icon-trash"></i></button></td>
</tr>
php Code :
public function add(){
// Form Inputs
$invoice = $this->input->post('invoice');
$date = $this->input->post('date');
$created_by = $this->input->post('created_by');
$products = $this->input->post('products');
$qnt = $this->input->post('qnt[]');
$unit_price = $this->input->post('unit_price[]');
$pack_size = $this->input->post('pack_size[]');
$unit_pack = $this->input->post('unit_pack[]');
$total_kg = $this->input->post('total_kg[]');
$total_price = $this->input->post('total_price[]');
$payed = $this->input->post('payed');
$price_less = $this->input->post('price_less');
$price_discount = $this->input->post('price_discount');
$price_due = $this->input->post('price_due');
$grand_total = $this->input->post('grand_total');
$payMethod = $this->input->post('payMethod');
$bank_name = $this->input->post('bank_name');
$cheque_no = $this->input->post('cheque_no');
$bank_acc_no = $this->input->post('bank_acc_no');
for($i = 0; $i < count($qnt); $i++){
$purchaseData = array(
'invoice_no' => $invoice,
'date' => $date,
'product_id' => $products,
'create_date' => $created_by,
'qnt' => $qnt[$i],
'unit_price' => $unit_price,
'pack_size' => $pack_size,
'unit_pack' => $unit_pack,
'total_kg' => $total_kg,
'total_price' => $total_price,
'payed' => $payed,
'price_less' => $price_less,
'price_discount' => $price_discount,
'price_due' => $price_due,
'grand_total' => $payMethod,
'payMethod' => $grand_total,
'bank_name' => $bank_name,
'cheque_no' => $cheque_no,
'bank_acc_no' => $bank_acc_no
);
$PurchaseQuery = $this->db->insert('purchase', $purchaseData);
if($PurchaseQuery){
$purchaseAdded = "Product Purchase Add.";
$this->session->set_flashdata('purchaseAdded', $purchaseAdded);
redirect('Purchase');
}
}
}
Please Help. I'm Using CI.

the requirement i quit different . what you can do is ? instead of looping through items . i mean
count($qnt)
just json_encode() the multiple items
or change your pattern and normalize you tables
to put order and items of orders in 2 different table

Please do this.
public function add(){
// Form Inputs
$invoice = $this->input->post('invoice');
$date = $this->input->post('date');
$created_by = $this->input->post('created_by');
$products = $this->input->post('products');
$qnt = $this->input->post('qnt[]');
$unit_price = $this->input->post('unit_price[]');
$pack_size = $this->input->post('pack_size[]');
$unit_pack = $this->input->post('unit_pack[]');
$total_kg = $this->input->post('total_kg[]');
$total_price = $this->input->post('total_price[]');
$payed = $this->input->post('payed');
$price_less = $this->input->post('price_less');
$price_discount = $this->input->post('price_discount');
$price_due = $this->input->post('price_due');
$grand_total = $this->input->post('grand_total');
$payMethod = $this->input->post('payMethod');
$bank_name = $this->input->post('bank_name');
$cheque_no = $this->input->post('cheque_no');
$bank_acc_no = $this->input->post('bank_acc_no');
$purchaseData = array(
'invoice_no' => $invoice,
'date' => $date,
'product_id' => $products,
'create_date' => $created_by,
'qnt' => $qnt[$i],
'unit_price' => $unit_price,
'pack_size' => $pack_size,
'unit_pack' => $unit_pack,
'total_kg' => $total_kg,
'total_price' => $total_price,
'payed' => $payed,
'price_less' => $price_less,
'price_discount' => $price_discount,
'price_due' => $price_due,
'grand_total' => $payMethod,
'payMethod' => $grand_total,
'bank_name' => $bank_name,
'cheque_no' => $cheque_no,
'bank_acc_no' => $bank_acc_no
);
$PurchaseQuery = $this->db->insert('purchase', $purchaseData);
if($PurchaseQuery){
$purchaseAdded = "Product Purchase Add.";
$this->session->set_flashdata('purchaseAdded', $purchaseAdded);
redirect('Purchase');
}
}
and let me know the result.

Related

Distinct in foreach loop. To many result because of two loops

I've a custom system that provides adding new information in custom columns.
I've two tables in my database. One for my value data and the second for the columns (data fieds).
Above you see a image from my form that is build by custom data fields with data per field.
Only in my for each i get for every data a extra loop so that is why i got from every data field two. How can I fix this?
<?php foreach ($list as $key => $value) { ?>
<?php foreach ($dataList as $data) { ?>
<div class="row clearfix">
<div class="col-xl-12">
<div class="form-group form-group-default">
<label><?php echo ucfirst($key); ?></label>
<?php if($key == $data['name']) { ?>
<input type="text" class="form-control" name="value_<?php echo trim($data['name']); ?>" value="<?php echo trim($data['value']); ?>" required>
<?php }else{ ?>
<input type="text" class="form-control" name="value_<?php echo trim($data['name']); ?>" placeholder="<?php echo ucfirst($key); ?>">
<?php } ?>
</div>
</div>
</div>
<?php } ?>
<?php } ?>
$list you'll find a list of data fields and in $dataList you'll find records of data.
Database structure:
data:
['id','hash','field_id','value']
Example of data:
['id' => 1, 'hash' => 123, 'field_id' => 1, 'value' => 'food']
Fields:
['id','name']
Example of fields:
['id' => 1, 'name' => 'firstname']
Below you'll find the foreach variables:
$data = processing('read', 'data JOIN fields ON data.field_id = fields.id', ['data.value,data.uid,fields.name,data.id,fields.category_id'], 'uid = "' . trim($_GET['datalist']) . '"', true);
$dataItem = processing('read', 'data JOIN fields ON data.field_id = fields.id', ['fields.category_id'], 'uid = "' . trim($_GET['datalist']) . '"');
$fieldList = processing('read', 'fields', ['name'], 'category_id = "'. trim($dataItem['category_id']) . '"',true);
$list = [];
foreach($fieldList as $key => $value) {
$list[$value['name']] = $value['name'];
}
Update:
I've update my own question because the other answers didn't resolved my problem. The only problem on my answer is, that when I update it doesnt look at the id of the item but at the name, so i can't save two items with the same name.
<?php foreach ($dataItems as $key => $value) { ?>
<div class="row clearfix">
<div class="col-xl-12">
<div class="form-group form-group-default">
<label><?php echo ucfirst($key); ?></label>
<input type="text" placeholder="<?php echo ucfirst($key); ?>" class="form-control" name="<?php echo trim($key); ?>" value="<?php echo trim($value); ?>">
</div>
</div>
</div>
<?php } ?>
method:
public function getDataListItems(int $category, array $list) {
global $dbh;
$query = 'SELECT data.value, data.uid, fields.name FROM data JOIN fields ON data.field_id = fields.id WHERE fields.category_id = "' . trim($category) . '" ORDER BY uid';
$sql = $dbh->prepare($query);
$sql->execute();
$values = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as $row) {
if (!isset($items[$row['uid']])) {
$items[$row['uid']] = array_fill_keys($list, ''); // if it needs to dynamically generated
$items[$row['uid']]['uid'] = $row['uid'];
}
$items[$row['uid']][$row['name']] = $row['value'];
}
return $items;
}
Return:
array (
'7d1f4f8e906245f' =>
array (
'Voornaam' => 'Bettina',
'Achternaam' => 'Les',
'Initialen' => 'pop',
'uid' => '7d1f4f8e906245f',
),
'7d1f4f8e906245g' =>
array (
'Voornaam' => 'Simone',
'Achternaam' => '',
'Initialen' => '',
'uid' => '7d1f4f8e906245g',
),
'7d1f4f8e906245l' =>
array (
'Voornaam' => 'test',
'Achternaam' => 'Kül',
'Initialen' => 'lol',
'uid' => '7d1f4f8e906245l',
),
'7d1f4f8e906245s' =>
array (
'Voornaam' => 'Joshua',
'Achternaam' => 'Mas',
'Initialen' => '',
'uid' => '7d1f4f8e906245s',
),
'gGcYEJdRYJ1vqcn' =>
array (
'Voornaam' => '',
'Achternaam' => 'Hello',
'Initialen' => '',
'uid' => 'gGcYEJdRYJ1vqcn',
),
)

Array in Codeigniter

I had simple key in the totalwithouttax with 3000, totaltax with 10 and totalamtincltax with 2000 in my interface.
And I had echo the array, the totaltax and totalamtincltax echo the right value that I key in, But totalwithouttax echo 1000 only and data inserted in database is 1.000000.
Please help me. Thank You.
Controller:
$custTd = $post['id'];
$custMame = $post['name'];
$custEmail = $post['email'];
$custAddr = $post['address'];;
$custTel = $post['telno'];
$remarks = $post['remark'];
$paymentOption = $post['options'];
$promoCode = $post['promo_code'];
$arraySize = count($post['totalwithouttax']);
for($i=0; $i<$arraySize; $i++){
$totalWithoutTax = $post['totalwithouttax'][$i]; //$post['totalwithouttax'];
$totalTax = $post['totaltax'][$i]; //$post['totaltax'];
$totalAmtInclTax = $post['totalamtincltax'][$i];//$post['totalamtincltax'];
//MASSAGE DATA TO BE INSERTED TO ARRAY
$orderHeader = array(
'user_id' => $custTd,
'status' => 1,
'cust_name' => $custMame,
'cust_email' => $custEmail,
'cust_addr' => $custAddr,
'cust_tel' => $custTel,
'remarks' => $remarks,
'pay_option' => $paymentOption,
'total_without_tax' => $totalWithoutTax,
'total_tax' => $totalTax, 'total_amt_incl_tax' => $totalAmtInclTax,
'epp_first_payment' => $eppFirstPayment,
);
//INSERT ORDER HEADER
$orderHeaderId = $this->order->InsertOrderHeader($orderHeader);
view:
<tr class="item-details">
<td><span class="rowNumber">1</span></td>
<td class="">
<?php
$options = array(
'' => '~Choose An Item~'
);
foreach ($item as $rows){
$options[$rows->id] = $rows->item_name;
}
$select = array(
'id' => 'item_id',
'class' => 'form-control'
);
echo form_dropdown('item_id[]', $options,set_value('item_name'),$select);
?>
</td>
<td class=""><input type="number" class="item-qty" name="qty[]" min="0.00" /></td>
<td><input type="number" name="weight[]" class="weight" step="any" /></td>
<td><input type="number" name="transportation[]" class="transporation" step="any" /></td>
<td><input type="text" id="gp[]" name="gp[]" value="" /></td>
<td><input type="text" id="discount[]" name="discount[]" value=""/></td>
<td><input type="text" id="unit_price[]" name="unit_price[]" value="" /></td>
<td align="right">
<input type="text" id="totalwithouttax" name="totalwithouttax[]" value="">
</td>
<td align="right">
<input type="text" id="totaltax" name="totaltax[]" value="">
</td>
<td align="right">
<input type="text" id="totalamtincltax" name="totalamtincltax[]" value="">
</td>
</tr><br/>
You are wrong way calling post method
$custTd = $_POST['id'];
$custMame = $_POST['name'];
$custEmail = $_POST['email'];
$custAddr = $_POST['address'];;
$custTel = $_POST['telno'];
$remarks = $_POST['remark'];
$paymentOption = $_POST['options'];
$promoCode = $_POST['promo_code'];
$arraySize = count($post['totalwithouttax']);
for($i=0; $i<=$arraySize; $i++){
$totalWithoutTax = $_POST['totalwithouttax'][$i];
$totalTax = $_POST['totaltax'][$i]; //$post['totaltax'];
$totalAmtInclTax = $_POST['totalamtincltax'][$i];
//MASSAGE DATA TO BE INSERTED TO ARRAY
$orderHeader = array(
'user_id' => $custTd,
'status' => 1,
'cust_name' => $custMame,
'cust_email' => $custEmail,
'cust_addr' => $custAddr,
'cust_tel' => $custTel,
'remarks' => $remarks,
'pay_option' => $paymentOption,
'total_without_tax' => $totalWithoutTax,
'total_tax' => $totalTax,
'total_amt_incl_tax' => $totalAmtInclTax,
'epp_first_payment' => $eppFirstPayment,
);
}

Insert Multiple Rows into Database in Codeigniter

I got 3 constant rows with few columns like Item,Quantity,Weight...... in a row, in my Interface.
When I selected the data in the rows and submit form, only the 3rd row data will be inserted into the database.
I want each rows that contain data insert into the database. Any solution for this? Thank You.
Updated::
I had tried to use the PHP array and below is the updated code.But I had stucked at the foreach part, I want to insert the data into the database.
My View:
<tr class="item-details">
<td><span class="rowNumber">1</span></td>
<td class="">
<?php
$options = array(
'' => '~Choose An Item~'
);
foreach ($item as $rows){
$options[$rows->id] = $rows->item_name;
}
$select = array(
'name' => 'item_name[]',
'id' => 'item_name',
'class' => 'form-control'
);
echo form_dropdown('item', $options,set_value('item_name'),$select);
?>
</td>
<td class=""><input type="number" class="item-qty" name="qty[]"/></td>
<td><input type="number" name="weight[]" class="weight" /></td>
<td><input type="text" name="promo_code[]" value=""/></td>
<td><input type="text" name="gp[]" value=""/></td>
<td><input type="text" name="discount[]" value=""/></td>
<td><input type="text" name="unit_price[]" value=""/></td>
<td align="right" class="totalwithouttax">0.00</td>
<td align="right" class="totaltax">0.00</td>
<td align="right" class="totalamtincltax">0.00</td>
</tr><br/>
<tr class="item-details">
<td><span class="rowNumber">2</span></td>
<td class="">
<?php
$options = array(
'' => '~Choose An Item~'
);
foreach ($item as $rows){
$options[$rows->id] = $rows->item_name;
}
$select = array(
'name' => 'item_name[]',
'id' => 'item_name',
'class' => 'form-control'
);
echo form_dropdown('item', $options,set_value('item_name'),$select);
?>
</td>
<td class=""><input type="number" class="item-qty" name="qty[]"/></td>
<td><input type="number" name="weight[]" class="weight" /></td>
<td><input type="text" name="promo_code[]" value=""/></td>
<td><input type="text" name="gp[]" value=""/></td>
<td><input type="text" name="discount[]" value=""/></td>
<td><input type="text" name="unit_price[]" value=""/></td>
<td align="right" class="totalwithouttax">0.00</td>
<td align="right" class="totaltax">0.00</td>
<td align="right" class="totalamtincltax">0.00</td>
</tr><br/>
<tr class="item-details">
<td><span class="rowNumber">3</span></td>
<td class="">
<?php
$options = array(
'' => '~Choose An Item~'
);
foreach ($item as $rows){
$options[$rows->id] = $rows->item_name;
}
$select = array(
'name' => 'item_name[]',
'id' => 'item_name',
'class' => 'form-control'
);
echo form_dropdown('item', $options,set_value('item_name'),$select);
?>
</td>
<td class=""><input type="number" class="item-qty" name="qty[]"/></td>
<td><input type="number" name="weight[]" class="weight" /></td>
<td><input type="text" name="promo_code[]" value=""/></td>
<td><input type="text" name="gp[]" value=""/></td>
<td><input type="text" name="discount[]" value=""/></td>
<td><input type="text" name="unit_price[]" value=""/></td>
<td align="right" class="totalwithouttax">0.00</td>
<td align="right" class="totaltax">0.00</td>
<td align="right" class="totalamtincltax">0.00</td>
</tr><br/>
Controller:
//***************** ORDER ITEM ********************
$orderID = 1;
$productId = $this->input->post('product_id');
$itemName = $_POST['item_name'];//$this->input->post('item_name');
$qty = $this-> $_POST['qty'];//input->post('qty');
$weight = $this-> $_POST['weight'];//input->post('weight');
$unitPrice = $_POST['unit_price'];//$this->input->post('unit_price');
$transportationPrice = $this->input->post('transportation_price');
$itemType = $this->input->post('item_type');
$gp = $this-> $_POST['gp'];//input->post('gp');
$tax = $this->input->post('tax');
$amtInclTax = $this->input->post('amt_incl_tax');
$amtWithoutTax = $this->input->post('amt_without_tax');
$taxCode = $this->input->post('tax_code');
$orderItems = array (
'order_id' => $orderHeaderId ,
'product_id' => 7 ,
'item' => $itemName ,
'qty' => $qty ,
'weight' => $weight ,
'unit_price' => $unitPrice ,
'transportation_price' => 0 ,
'item_type' => 'GOLD' ,
'gp' => $gp,
'discount' => $discount,
'amt_without_tax' => 10,
'tax' => 20 ,
'amt_incl_tax' => 30,
'tax_code' => 40 ,
);
echo '<pre>'; print_r($orderItems); echo '</pre>';
foreach($itemName as $key => $iN){
//stuck at here
}
$orderHeaderId = $this->order->InsertItemData($orderHeaderId,$orderHeader,$orderItems);
Model:
public function InsertItemData($orderHeaderId,$orderHeader,$orderItems){
//take order_id from 'order' table //from InsertData(model) function
$orderHeaderId = $this->InsertData($orderHeader);
// Inserting Order Item
if($orderItems){
$this->db->insert_batch('order_items', $orderItems);
}
}
First make your all 3 portion of HTML form input name array like
<input type="number" class="item-qty" name="qty[]"/>
<input type="number" name="weight" class="weight[]" />
...
Then loop your data array as
$qty = $this->input->post('qty', TRUE);
$weight = $this->input->post('weight', TRUE);
$orderItems = array();
for ($i = 0; $i < count($qty); $i++) {
if ($qty[$i]) {
$orderItems[] = array (
'order_id' => $orderHeaderId ,
'product_id' => 7 ,
'item' => 'TEST' ,
'qty' => $qty[$i] ,
'weight' => $weight[$i]
...
);
}
}
And now you may use insert_batch method as
if ($orderItems) {
$this->db->insert_batch('table_name', $orderItems);
}
You could modify each of the codes like below.
Controller :
$orderID = 1;
$productId = $this->input->post('product_id');
$itemName = $_POST['item_name'];//$this->input->post('item_name');
$qty = $this-> $_POST['qty'];//input->post('qty');
$weight = $this-> $_POST['weight'];//input->post('weight');
$unitPrice = $_POST['unit_price'];//$this->input->post('unit_price');
$transportationPrice = $this->input->post('transportation_price');
$itemType = $this->input->post('item_type');
$gp = $this-> $_POST['gp'];//input->post('gp');
$tax = $this->input->post('tax');
$amtInclTax = $this->input->post('amt_incl_tax');
$amtWithoutTax = $this->input->post('amt_without_tax');
$taxCode = $this->input->post('tax_code');
$orderItems = array();
for ($i = 0; $i < count($qty); $i++) {
if ($qty[$i]) {
$orderItems[] = array (
// 'order_id' => $orderHeaderId ,
'product_id' => 7 ,
'item' => $itemName[$i] ,
'qty' => $qty[$i] ,
'weight' => $weight[$i] ,
'unit_price' => $unitPrice[$i] ,
'transportation_price' => 0 ,
'item_type' => 'GOLD' ,
'gp' => $gp[$i],
'discount' => $discount[$i],
'amt_without_tax' => 10,
'tax' => 20 ,
'amt_incl_tax' => 30,
'tax_code' => 40 ,
);
}
}
$this->order->InsertItemData($orderHeader,$orderItems);
Model :
public function InsertItemData($orderHeader,$orderItems) {
//take order_id from 'order' table //from InsertData(model) function
$orderHeaderId = $this->InsertData($orderHeader);
if($orderItems) {
// append order_id array into each order item
foreach ($orderItems as $key => $item) {
$orderItems[$key] = array('order_id' => $orderHeaderId) + $orderItems[$key];
}
// Inserting Order Item
$this->db->insert_batch('order_items', $orderItems);
}
}

How to use two foreach to insert data in database

I have two arrays from my view.I need to insert their data corresponding to each other.
Below is the My view
<?php foreach ($seats as $seat):?>
<tr>
<td><input type="checkbox" name="seat_id[]" value=<?php echo $seat->seatNumber;?>></td>
<td><?php echo $seat->seatLabel;?></td>
<td><input type="hidden" name="seat_label[]" value="<?php echo $seat->seatLabel;?>"></td>
</tr>
<?php endforeach;?>
From above view seat_id and seat_label carries values that have to be stored in database
This is my controller
if($this->form_validation->run()){
$seat_ids = $this->input->post("seat_id[]");
$seat_labels = $this->input->post("seat_label[]");
$busNumber = $this->input->post("busNumber");
$bookingDate = $this->input->post("bookingDate");
$reportingTime = $this->input->post("reportingTime");
$departureTime = $this->input->post("departureTime");
$this->load->model('Queries');
$insert = $this->Queries->saveMessage($seat_ids, $seat_labels, $busNumber, $bookingDate, $reportingTime, $departureTime);
This is My model
public function saveMessage($seat_ids, $seat_labels, $busNumber, $bookingDate, $reportingTime, $departureTime){
foreach($seat_ids as $seat_id )
foreach($seat_labels as $seat_label ){
{
$record = array(
'seatNumber' => $seat_id,
'seatLabel' => $seat_label,
'bookingDate' => $bookingDate,
'reportingTime' => $reportingTime,
'departureTime' => $departureTime,
'busNumber' => $busNumber,
'seatUse' => 'Enabled',
'seatStatus' => 'Available',);
$this->db->insert('schedule', $record);
}
Hope this will help you :
Use insert_batch instead of insert like this :
public function saveMessage($seat_ids, $seat_labels, $busNumber, $bookingDate, $reportingTime, $departureTime)
{
foreach($seat_ids as $key => $seat_id )
{
$record[] = array(
'seatNumber' => $seat_id,
'seatLabel' => $seat_labels[$key],
'bookingDate' => $bookingDate,
'reportingTime' => $reportingTime,
'departureTime' => $departureTime,
'busNumber' => $busNumber,
'seatUse' => 'Enabled',
'seatStatus' => 'Available');
}
$this->db->insert_batch('schedule', $record);
}
For more :https://www.codeigniter.com/user_guide/database/query_builder.html#inserting-data
your code should read
foreach($seat_ids as $seat_id ){
foreach($seat_labels as $seat_label ){
$record = array(
'seatNumber' => $seat_id,
'seatLabel' => $seat_label,
'bookingDate' => $bookingDate,
'reportingTime' => $reportingTime,
'departureTime' => $departureTime,
'busNumber' => $busNumber,
'seatUse' => 'Enabled',
'seatStatus' => 'Available',);
$this->db->insert('schedule', $record);
}
}
if your the keys from $seat_id and $seat_label match you can do it with only one foreach like this:
foreach($seat_ids as $seat_key => $seat_id ) {
$record = array(
'seatNumber' => $seat_id,
'seatLabel' => $seat_label[$seat_key],
'bookingDate' => $bookingDate,
'reportingTime' => $reportingTime,
'departureTime' => $departureTime,
'busNumber' => $busNumber,
'seatUse' => 'Enabled',
'seatStatus' => 'Available',);
$this->db->insert('schedule', $record);
}
Considering that you are using JSON to submit the form data and order among array is maintained.
You may try :
$i = 0;
foreach($seat_ids as $seat_id )
{
$record = array(
'seatNumber' => $seat_id,
'seatLabel' => $seat_labels[$i],
'bookingDate' => $bookingDate,
'reportingTime' => $reportingTime,
'departureTime' => $departureTime,
'busNumber' => $busNumber,
'seatUse' => 'Enabled',
'seatStatus' => 'Available',);
$this->db->insert('schedule', $record);
$i++;
}
Currently the form does not have a seat-label relation. if you do not tick all ids, then the labels after that will correspond to the wrong id (i.e. the ids' posted array is smaller than the labels' array)
Hence you will have to introduce the necessary relation into the form names:
<input type="checkbox" name="seat[{index}][id]" value="{id}">
<input type="hidden" name="seat[{index}][label]" value="{label}">
If that submits, you can now check if both boxes were ticked
// using $_POST for simplicity
$seats = array_filter($_POST['seat'], function (array $row) {
return count($row) === 2;
});
Now you have an array with corresponding ids/labels where only one loop is needed.
EDIT: overlooked that the second input is a hidden field, but that didn't affect the problem at all.

Insert_batch Error Codeigniter 3.1.4

A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: database/DB_query_builder.php
Line Number: 1539
Backtrace: File: D:\xampp\htdocs\visio\application\models\projectmodel.php
Line: 56
Function: insert_batch
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Array' at line 1
INSERT INTO paymentsize () VALUES ('8'), ('2017-06-07'), ('Residential'), ('L'), ('120'), ('200'), ('10000'), ('15000'), ('30'), ('12000'), ('40'), ('1000'), ('60'), ('125000'), ('10'), ('10000'), ('15000'), ('20000'), Array
Filename: D:/xampp/htdocs/visio/system/database/DB_driver.php
Line Number: 691
My Controller is:
public function store_payment()
{
$post = array();
$post = $this->input->post(NULL,TRUE);
$count=count($this->input->post('pro_id'));
echo CI_VERSION;
for($i = 0; $i < $count; $i++){
$post []= array(
'pro_id' => $post['pro_id'][$i],
'date_add' => $post['date_add'][$i],
'category' => $post['category'][$i],
'type' => $post['type'][$i],
'size' => $post['size'][$i],
'counts' => $post['counts'][$i],
'booking' => $post['booking'][$i],
'confirmation' => $post['confirmation'][$i],
'confirm_days' => $post['confirm_days'][$i],
'allocation' => $post['allocation'][$i],
'allocate_days' => $post['allocate_days'][$i],
'm_installment' => $post['m_installment'][$i],
'month' => $post['month'][$i],
'y_instalment' => $post['y_instalment'][$i],
'halfyear' => $post['halfyear'][$i],
'leveling' => $post['leveling'][$i],
'demarcation' => $post['demarcation'][$i],
'possession' => $post['possession'][$i]
);
}
$this->projects->add_payment($post);
}
My Model is:
public function add_payment($array)
{
// echo "<pre>";
// print_r($array);
// exit();
return $this->db->insert_batch('paymentsize',$array);
}
My View is:
<tbody>
<input type="hidden" name="pro_id[]" value="<?= $project->pro_id; ?>" >
<tr>
<td width="14%">
<div class="col-lg-10">
<div class="form-group form-black label-floating is-empty">
<label class="control-label" style="margin-top: -10px;">Date</label>
<input type="date" name="date_add[]" value="<?php echo date('Y-m-d'); ?>" class="form-control" >
<span class="material-input"></span>
</div>
</div>
</td>
<td width="14%">
<div class="col-lg-10">
<div class="form-group form-black label-floating is-empty">
<label class="control-label">Plot Category</label>
<select name="category[]" class="form-control">
<option> </option>
<option>Residential</option>
<option>Commercial</option>
</select>
<span class="material-input"></span>
</div>
</div>
</td>
<td>
if i use print_r it shows all array elements with respective Values.. but it is not inserting in DB Table..
my view has a table with 17 text fields... i just mention few for an Example...
waiting for help.... :)
Thank you in advance...
Change your controller as following code,
public function store_payment()
{
$post = array();
$post = $this->input->post(NULL,TRUE);
$count=count($this->input->post('pro_id'));
echo CI_VERSION;
for($i = 0; $i < $count; $i++){
$post = array(
'pro_id' => $post['pro_id'][$i],
'date_add' => $post['date_add'][$i],
'category' => $post['category'][$i],
'type' => $post['type'][$i],
'size' => $post['size'][$i],
'counts' => $post['counts'][$i],
'booking' => $post['booking'][$i],
'confirmation' => $post['confirmation'][$i],
'confirm_days' => $post['confirm_days'][$i],
'allocation' => $post['allocation'][$i],
'allocate_days' => $post['allocate_days'][$i],
'm_installment' => $post['m_installment'][$i],
'month' => $post['month'][$i],
'y_instalment' => $post['y_instalment'][$i],
'halfyear' => $post['halfyear'][$i],
'leveling' => $post['leveling'][$i],
'demarcation' => $post['demarcation'][$i],
'possession' => $post['possession'][$i]
);
}
$this->projects->add_payment($post);
}
You used $post for two purpose, change your controller codes as following code:
public function store_payment()
{
$post = $this->input->post(NULL,TRUE);
$count=count($this->input->post('pro_id'));
echo CI_VERSION;
$data = array();
for($i = 0; $i < $count; $i++){
$data []= array(
'pro_id' => $post['pro_id'][$i],
'date_add' => $post['date_add'][$i],
'category' => $post['category'][$i],
'type' => $post['type'][$i],
'size' => $post['size'][$i],
'counts' => $post['counts'][$i],
'booking' => $post['booking'][$i],
'confirmation' => $post['confirmation'][$i],
'confirm_days' => $post['confirm_days'][$i],
'allocation' => $post['allocation'][$i],
'allocate_days' => $post['allocate_days'][$i],
'm_installment' => $post['m_installment'][$i],
'month' => $post['month'][$i],
'y_instalment' => $post['y_instalment'][$i],
'halfyear' => $post['halfyear'][$i],
'leveling' => $post['leveling'][$i],
'demarcation' => $post['demarcation'][$i],
'possession' => $post['possession'][$i]
);
}
$this->projects->add_payment($data);
}

Categories