Generate a custom HTML form using array values with PHP - php

Problem:
I am trying to generate a custom HTML form with help of values in an array using PHP.
The PHP code ($row['Key'] will contain W, B and R):
$numbers[$row['Key']] = array (
'C' =>
array (
'BO' => $row['BO'],
'BT' => $row['BT']),
'D' =>
array (
'MF' => $row['MF'],
'MT' => $row['MT'])
);
Array produced with PHP:
Array
(
[W] => Array
(
[C] => Array
(
[BO] => 36
[BT] => 63
)
[D] => Array
(
[MF] => 54
[MT] => 63
)
)
[B] => Array
(
[C] => Array
(
[BO] => 60
[BT] => 105
)
[D] => Array
(
[MF] => 90
[MT] => 105
)
)
[R] => Array
(
[C] => Array
(
[BO] => 12
[BT] => 21
)
[D] => Array
(
[MF] => 18
[MT] => 24
)
)
)
The outcome should look like the following. Notice the combination of W/B/R and BO/BT/MF/MT.
<table>
<tbody>
<tr>
<td>W</td>
<td><input type="text" name="WBO" id="WBO" value="36"></td>
<td><input type="text" name="WBT" id="WBT" value="63"></td>
<td><input type="text" name="WMF" id="WMF" value="54"></td>
<td><input type="text" name="WMT" id="WMT" value="63"></td>
</tr>
<tr>
<td>B</td>
<td><input type="text" name="BBO" id="BBO" value="60"></td>
<td><input type="text" name="BBT" id="BBT" value="105"></td>
<td><input type="text" name="BMF" id="BMF" value="90"></td>
<td><input type="text" name="BMT" id="BMT" value="105"></td>
</tr>
<tr>
<td>R</td>
<td><input type="text" name="RBO" id="RBO" value="12"></td>
<td><input type="text" name="RBT" id="RBT" value="21"></td>
<td><input type="text" name="RMF" id="RMF" value="18"></td>
<td><input type="text" name="RMT" id="RMT" value="24"></td>
</tr>
</tbody>
</table>

http://php.net/manual/en/control-structures.foreach.php

without using 3 foreach loops
$var = print_r($numbers, true);
$table = preg_replace_callback(
"{.*?[^ ][ ]{4}\[(\S+)\].*?[^ ][ ]{8}\)}s",
"func",
$var);
$table= preg_replace('{\n[^<].*}','',$table);
echo "<table>{$table}</table>";
function: (count space to find array level)
function func($matches)
{
$table='';
$k=$matches[1];
$t=$matches[0];
$tr = preg_replace('{.*?[^ ][ ]{20}\[(\S+)\].*?=>.*?(\S+)}s',PHP_EOL."<td><input type='text' id='{$k}$1' name='{$k}$1' value='$2'></td>",$t);
$table .= "<tr>".PHP_EOL;
$table .= "<td>{$k}<td>{$tr}".PHP_EOL;
$table .= "</tr>".PHP_EOL;
return $table;
}
echo
<table><tr>
<td>W<td>
<td><input type='text' id='WBO' name='WBO' value='36'></td>
<td><input type='text' id='WBT' name='WBT' value='63'></td>
<td><input type='text' id='WMF' name='WMF' value='54'></td>
<td><input type='text' id='WMT' name='WMT' value='63'></td>
</tr>
<tr>
<td>B<td>
<td><input type='text' id='BBO' name='BBO' value='60'></td>
<td><input type='text' id='BBT' name='BBT' value='105'></td>
<td><input type='text' id='BMF' name='BMF' value='90'></td>
<td><input type='text' id='BMT' name='BMT' value='105'></td>
</tr>
</table>

Should be fairly easy to step through this array with foreach().
[ghoti#pc ~]$ cat doit.php
#!/usr/local/bin/php
<?php
printf("<table>\n <tbody>\n");
$numbers=array(
'W' => array(
'C' => array( 'BO' => 36, 'BT' => 63),
'D' => array( 'MF' => 54, 'MT' => 63),
),
'B' => array(
'C' => array( 'BO' => 60, 'BT' => 105),
'D' => array( 'MF' => 90, 'MT' => 105),
),
);
$fmt1 = "\t<tr>\n"
. "\t\t<td>%s</td>\n"
. "%s"
. "\t</tr>\n";
$fmt2 = "\t\t<td><input type='text' name='%s%s' id='%s%s' value='%s'></td>\n";
foreach ($numbers as $index1 => $line1) {
foreach ($line1 as $index2 => $line2) {
foreach ($line2 as $index3 => $value) {
$output .= sprintf($fmt2, $index1, $index3, $index1, $index3, $value);
}
}
printf($fmt1, $index1, $output);
$output = "";
}
printf(" </tbody>\n</table>\n");
And the output:
[ghoti#pc ~]$ ./doit.php
<table>
<tbody>
<tr>
<td>W</td>
<td><input type='text' name='WBO' id='WBO' value='36'></td>
<td><input type='text' name='WBT' id='WBT' value='63'></td>
<td><input type='text' name='WMF' id='WMF' value='54'></td>
<td><input type='text' name='WMT' id='WMT' value='63'></td>
</tr>
<tr>
<td>B</td>
<td><input type='text' name='BBO' id='BBO' value='60'></td>
<td><input type='text' name='BBT' id='BBT' value='105'></td>
<td><input type='text' name='BMF' id='BMF' value='90'></td>
<td><input type='text' name='BMT' id='BMT' value='105'></td>
</tr>
</tbody>
</table>
[ghoti#pc ~]$

this?
echo "<table><tbody>";
foreach((array)$numbers as $key=>$val) {
echo "<tr><td>".$key."</td>";
foreach((array)$val as $key2=>$val2) {
foreach((array)$val2 as $key3=>$val3) {
echo '<td><input type="text" name="'.$key.$key3.'" id="'.$key.$key3.'" value="'.$val3.'"></td>';
}
}
echo "</tr>";
}
echo "</tbody></table>";

Check this code dude.
<table>
<tbody>
<?php
foreach($numbers as $key=>$sarray){
echo "<tr>";
echo "<td>$key</td>";
foreach($sarray as $key1=>$sarray1){
foreach($sarray1 as $fname=>$fvalue){
echo '<td><input type="text" name="'.$fname.'" id="'.$fname.'" value="'.$fvalue.'"></td>';
}
}
echo "</tr>";
}
?>
</tbody>
</table>

Related

How to insert an array in database in Codeigniter?

I have a problem in inserting array in the database in Codeigniter, I tried following way but it gives an error "Message: Illegal string offset 'year'", "Message: Illegal string offset 'month'" and so on..., I really confused about how to solve this, please help.
this is the form:
<form action="<?php echo base_url();?>hr/Home/store_attendance" method="post"
id="student_attendance_entry">
<input type="hidden" name="year" value="<?php echo $year; ?>" />
<input type="hidden" name="month" value="<?php echo $month; ?>" />
<?php foreach($staffs as $staff): ?>
<table class="table table-striped table-bordered table-hover attendance_entry"
style="border:initial;border: 1px solid #ddd;" id="sample_editable_2">
<thead>
<tr>
<th style="width: 50px !important;">شماره</th>
<th align="center" style="width:auto%">آی دی</th>
<th align="center" style="width:15%">نام</th>
<th align="center" style="width:15%;"> ولد</th>
<th align="center" style="width:auto">حاضر</th>
<th align="center" style="width:auto">غیر حاضر</th>
<th align="center" style="width:auto">توضیحات</th>
</tr>
</thead>
<tbody>
<?php $a=1; foreach($staffs as $st):?>
<tr>
<td align="center" style="font-size: 11px"><?php echo $a;?></td>
<td align="center" style="font-size: 11px"><?php echo $st['s_id'];?></td>
<td align="center"><?php echo $st['dari_name'];?></td>
<td align="center"><?php echo $st['dari_fName'];?></td>
<td>
<input type="number" min="0" class="form-control" name="total_present_day[]"
value="<?php if($st['total_present']==null){echo '';}else{ echo $st['total_present'];}?>"
data="<?php echo $a;?>">
<input type="hidden" name="salary_type[]" id="salary_type" value="<?php echo $st['salary_type']?>">
</td>
<td>
<input type="number" min="0" class="form-control" name="total_absent_day[]"
value="<?php if($st['absent']==null){echo '';}else{ echo $st['absent'];}?>"
data="<?php echo $a;?>">
<input type="hidden" class="form-control" name="staff_id[]" value="<?php echo $st['s_id'];?>">
</td>
<td>
<textarea min="0" class="form-control" name="memo[]"
colspan='3' rowspan="1"
data="<?php echo $a;?>"><?php if($st['memo']==null){echo '';}else{ echo $st['memo'];}?></textarea>
</td>
</tr>
<?php $a++;endforeach;?>
</tbody>
</table>
<?php endforeach; ?>
<br>
<div class="form-actions right">
<a href="<?php echo base_url();?>student/school/attendance" class="btn default" data-dismiss="modal"><i
class="fa fa-close"></i> بستن</a>
<input type="submit" name="save" class="btn blue" value="ذخیره" />
</div>
this is the controller:
public function store_attendance()
{
$data=array(
'year' => $this->input->post('year'),
'month' => $this->input->post('month'),
'staff_id' => $this->input->post('staff_id'),
'total_present_day' => $this->input->post('total_present_day'),
'total_absent_day'=>$this->input->post('total_absent_day'),
'salary_type'=>$this->input->post('salary_type'),
'memo'=>$this->input->post('memo')
);
$this->dd($data);
// $this->dd($class);
$insert_att = $this->stuff_model->add_staff_attendance($data);
// var_dump($insert_att);
if($insert_att)
{
echo redirect(base_url().'hr/register_employee_attendance');
}
}
this is the model:
public function add_staff_attendance($data)
{
$this->db->trans_begin();
foreach ($data['total_present_day'] as $key => $value) {
{
$dataToSave = array(
'year' => $value['year'],
'month' => $value['month'],
'type_id'=>$value['salary_type'][$key],
'total_present' => $value['total_present_day'][$key],
'absent'=>$value['total_absent_day'][$key],
'memo'=>$value['memo'][$key],
'staf_id' => $value['staff_id'][$key]
);
$this->db->insert('staff_attendance', $dataToSave);
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return true;
}
}
}
I called $this->dd($data) in controller and this is the output:
array (
'Total' => 7,
)
array (
'year' => '1400',
'month' => '2',
'staff_id' =>
array (
0 => '3',
),
'total_present_day' =>
array (
0 => '26',
),
'total_absent_day' =>
array (
0 => '0',
),
'salary_type' => '1',
'memo' =>
array (
0 => 'dds',
),
)
And this is the result of echo '<pre>'; print_r($data); echo '</pre>'; In model:
Array
(
[year] => 1400
[month] => 1
[staff_id] => Array
(
[0] => 3
[1] => 1
)
[total_present_day] => Array
(
[0] => 26
[1] => 20
)
[total_absent_day] => Array
(
[0] => 0
[1] => 6
)
[salary_type] => Array
(
[0] => 1
[1] => 1
)
[memo] => Array
(
[0] => asfd
[1] => saef
)
)
Array
(
[year] => 1400
[month] => 1
[staff_id] => Array
(
[0] => 3
[1] => 1
)
[total_present_day] => Array
(
[0] => 26
[1] => 20
)
[total_absent_day] => Array
(
[0] => 0
[1] => 6
)
[salary_type] => Array
(
[0] => 1
[1] => 1
)
[memo] => Array
(
[0] => asfd
[1] => saef
)
)
Your submitted data is structured in a logical, minimalistic, yet irregular fashion. By reconfiguring the name attributes of the form fields in your view, you can largely reduce the lines of processing code in the controller and the model.
Move the hidden fields inside your foeach() loop and declare dynamic indexes. Effectively the named fields would resemble this:
<?php foreach($staffs as $index => $staff) { ?>
<input type="hidden" name="attendance[<?php echo $index; ?>]['year']">
<input type="hidden" name="attendance[<?php echo $index; ?>]['month']">
<input type="number" name="attendance[<?php echo $index; ?>]['total_present']">
<input type="hidden" name="attendance[<?php echo $index; ?>]['type_id']">
<input type="number" name="attendance[<?php echo $index; ?>]['absent']">
<input type="hidden" name="attendance[<?php echo $index; ?>]['staf_id']">
<textarea name="attendance[<?php echo $index; ?>]['memo']"></textarea>
<?php } ?>
The controller needs a validation/sanitization process and some restucturing before blindly passing data to the model. I will not go into the validation/sanitization, but you should iterate the data, and deny it from being saved if ANY of the values are inappropriate.
Controller:
public function store_attendance(): void
{
// Definitely validate and sanitize the rows of data before passing to model.
// This shortcut is for demonstrating how to batch insert
if ($this->stuff_model->add_staff_attendance($this->input->post('attendance'))) {
redirect(base_url() . 'hr/home/register_employee_attendance');
} else {
// reload view and explain what went wrong
}
}
Model:
public function add_staff_attendance(array $data): bool
{
return $this->db->insert_batch('staff_attendance', $data);
}
None of this answer was tested.
To leave the hidden fields outside of the loop, you will need to assemble the rows' values into the correct structure before sending to the model for batch_insertion.
$presentDays = $this->input->post('total_present_day');
if ($presentDay) {
$rows = [];
foreach ($presentDays as $i => $presentDay) {
$rows[] = [
'year' => $this->input->post('year'),
'month' => $this->input->post('month'),
'staf_id' => $this->input->post('staff_id')[$i],
'total_present' => $this->input->post('total_present_day')[$i],
'absent' => $this->input->post('total_absent_day')[$i],
'type_id' => $this->input->post('salary_type')[$i],
'memo' => $this->input->post('memo')[$i]
];
}
if ($this->stuff_model->add_staff_attendance($rows)) {
redirect(base_url() . 'hr/home/register_employee_attendance');
} else {
// reload view and explain what went wrong
}
}
public function add_staff_attendance($data)
{
$this->db->trans_begin();
foreach ($data['total_present_day'] as $key => $value) {
{
$dataToSave = array(
'year' => $data['year'], // this seems to be same for all
'month' => $data['month'], // this seems to be same for all
'type_id' => $value['salary_type'][$key], // please change name='salary_type[]' in your form
'total_present' => $value['total_present_day'][$key], // seems to be an array
'absent' => $value['total_absent_day'][$key], // seems to be an array
'memo' => $value['memo'][$key], // seems to be an array
'staf_id' => $value['staff_id'][$key] // seems to be an array
);
$this->db->insert('staff_attendance', $dataToSave);
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return true;
}
}
}
I solved my problem by changing some codes in the controller and model.
controller:
public function store_attendance()
{
$data = array();
$insert_att = 0;
$tst = $this->input->post('total_present_day');
for ($i=0; $i < count($tst); $i++) {
$data = array(
'year' => $this->input->post('year'),
'month' => $this->input->post('month'),
'staf_id' => $this->input->post('staff_id')[$i],
'total_present' => $this->input->post('total_present_day')[$i],
'absent'=>$this->input->post('total_absent_day')[$i],
'type_id'=>$this->input->post('salary_type')[$i],
'memo'=>$this->input->post('memo')[$i],
);
// var_dump($data);
$this->get_public_data->saveData('staff_attendance', $data);
}
echo redirect(base_url().'hr/home/rgisterAttendance');
}
Model:
public function add_staff_attendance($data)
{
$this->db->insert('staff_attendance', $data);
}
it seems that the error is in the controller, you must go through the array while it is saving.
public function store_attendance()
{
$data=array(
'year' => $this->input->post('year'),
'month' => $this->input->post('month'),
'staff_id' => $this->input->post('staff_id'),
'total_present_day' => $this->input->post('total_present_day'),
'total_absent_day'=>$this->input->post('total_absent_day'),
'salary_type'=>$this->input->post('salary_type'),
'memo'=>$this->input->post('memo')
);
foreach($data as $d):
$insert_att = $this->stuff_model->add_staff_attendance($d);
if($insert_att)
{
echo redirect(base_url().'hr/register_employee_attendance');
}
else
{
echo redirect(base_url().'hr/register_employee_attendance');
}
endforeach;
}
You should try something like it

how to create table using multiple dimensional array in php

Actually This are my real data from API.
$main2 = array(
'sup1' => array(
'01-Jun-2019-TO-03-Jun-2019' => array("connection_count" => 54, "source_type" => 'TATA'),
'04-Jun-2019-TO-08-Jun-2019' => array("connection_count" => 10, "source_type" => 'Rel'),
),
'sup2' => array(
'01-Jun-2019-TO-03-Jun-2019' => array("connection_count" => 54, "source_type" => 'TCS'),
'04-Jun-2019-TO-08-Jun-2019' => array("connection_count" => 55, "source_type" => 'Jio'),
),
);
We need same out put using this array.
we create table all date in header like first key date as display in header.
-then data display supplier sup1 in first row
sup2 in second row row
like below out put
|Supplier Name |01-Jun-2019-TO-03-Jun-2019 |04-Jun-2019-TO-08-Jun-2019|<br/>
|sup1|54|TATA|10|Rel|
<br/>
|sup2|54|TCS|55|JIO|
Here is your code modified:
<?php
$main2 = array(
'01-Jun-2019-TO-03-Jun-2019' => array(
'sup1' => array("connection_count" => 54, "source_type" => 'TATA'),
'sup2' => array("connection_count" => 10, "source_type" => 'Rel'),
),
'04-Jun-2019-TO-08-Jun-2019' => array(
'sup1' => array("connection_count" => 54, "source_type" => 'TCS'),
'sup2' => array("connection_count" => 55, "source_type" => 'Jio'),
),
);
$suplist = array('sup1', 'sup2');
echo "<table border=1><tr>";
echo "<td>Supplier Name</td>";
foreach ($main2 as $key => $value) {
echo "<td colspan=2>" . $key . "</td>";
}
echo "</tr>";
foreach ($suplist as $supplier) {
echo "<tr><td>$supplier</td>";
foreach ($main2 as $value) {
echo "<td>" . $value[$supplier]['connection_count'] . "</td>";
echo "<td>" . $value[$supplier]['source_type'] . "</td>";
}
echo "</tr>";
}
echo "</table>";
And here is sample output (reformatted for clarity):
<table border=1>
<tr>
<td>Supplier Name</td>
<td colspan=2>01-Jun-2019-TO-03-Jun-2019</td>
<td colspan=2>04-Jun-2019-TO-08-Jun-2019</td>
</tr>
<tr>
<td>sup1</td>
<td>54</td>
<td>TATA</td>
<td>54</td>
<td>TCS</td>
</tr>
<tr>
<td>sup2</td>
<td>10</td>
<td>Rel</td>
<td>55</td>
<td>Jio</td>
</tr>
</table>
Here is your code which works with updated input data format:
$main2 = array(
'sup1' => array(
'01-Jun-2019-TO-03-Jun-2019' => array("connection_count" => 54, "source_type" => 'TATA'),
'04-Jun-2019-TO-08-Jun-2019' => array("connection_count" => 10, "source_type" => 'Rel'),
),
'sup2' => array(
'01-Jun-2019-TO-03-Jun-2019' => array("connection_count" => 54, "source_type" => 'TCS'),
'04-Jun-2019-TO-08-Jun-2019' => array("connection_count" => 55, "source_type" => 'Jio'),
),
);
$suppliers = array_keys($main2);
$dateRanges = [];
foreach ($main2 as $supplierData) {
$dateRanges = array_merge($dateRanges, array_keys($supplierData));
}
$dateRanges = array_values(array_unique($dateRanges));
sort($dateRanges);
echo "<table border=1><tr>";
echo "<td>Supplier Name</td>";
foreach ($dateRanges as $dateRange) {
echo "<td colspan=2>" . $dateRange . "</td>";
}
echo "</tr>";
foreach ($suppliers as $supplier) {
echo "<tr><td>$supplier</td>";
foreach ($dateRanges as $dateRange) {
if (isset($main2[$supplier][$dateRange])) {
echo "<td>" . $main2[$supplier][$dateRange]['connection_count'] . "</td>";
echo "<td>" . $main2[$supplier][$dateRange]['source_type'] . "</td>";
} else {
echo "<td></td><td></td>";
}
}
echo "</tr>";
}
echo "</table>";
And here is sample output (formatted for clarity):
<table border=1>
<tr>
<td>Supplier Name</td>
<td colspan=2>01-Jun-2019-TO-03-Jun-2019</td>
<td colspan=2>04-Jun-2019-TO-08-Jun-2019</td>
</tr>
<tr>
<td>sup1</td>
<td>54</td>
<td>TATA</td>
<td>10</td>
<td>Rel</td>
</tr>
<tr>
<td>sup2</td>
<td>54</td>
<td>TCS</td>
<td>55</td>
<td>Jio</td>
</tr>
</table>

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);
}
}

Associative Multidimensional Array

I want to be able to use a variable (which is a value that is imputed in a textbox) in an
Associative Multidimensional Array and print out the rest of the array values associated with it.
here is what i have so far that doesnt work
<html>
<body>
<form method="post" action="newcal.php">
<table>
<tr>
<td> Item #: </td>
<td> <input type=text name= txtitem > <br> </td>
<td>
</td>
<td> <fieldset style = "width:60px">
<input type=submit value = "Get Data" name= getdata>
<input type=submit value = "Add to Cart" name= addto>
<input type=submit value = "Get Total" name= gettotal>
</fieldset>
</td>
</tr>
</table>
</form>
<?php
$item = isset($_POST['txtitem']);
$stuff = array(
array("id" => 1,"name" => "Apples","price" => 50 ),
array("id" => 2,"name" => "Pineapples","price" => 125 ),
array("id" => 3,"name" => "Mango","price" => 35 ),
array("id" => 4,"name" => "Banana","price" => 25 ),
array("id" => 5,"name" => "Naseberry","price" => 38 ));
if(isset($_POST['getdata']))
{
foreach ($stuff as $row)
{
if ($row['id'] == $item)
{
$name = $row['name'];
$price = $row['price'];
}
}
echo $name;
echo $price;
}
?>
</body>
</html>
I think your error is with the following line:
$item = isset($_POST['txtitem']);
$item is being set to a boolean value. You probably want something like this:
$item = (isset($_POST['txtitem']) ? intval($_POST['txtitem']) : null);

Categories