how to join the input from every row and save to database - php

i have this problem
this is the display from my view.php
id menu +1 +2 +3
1 bla_1 [] [] []
2 bla_2 [] [] []
3 bla_3 [] [] []
and this is my view code
<?php $i=1; foreach ($test as $row) : ?>
<tr>
<td><input type='hidden' name='id[]' value="<?php echo $row->menu_id ?>" /></td>
<td><input type="text" name="Menu" value="<?php echo $row->menu_nama ?>" disabled <td>
<td><input type="checkbox" name="<?php echo 'menu_id[]'; ?>" value="+1" /></td>
<td><input type="checkbox" name="<?php echo 'menu_id[]'; ?>" value="+2" /></td>
<td><input type="checkbox" name="<?php echo 'menu_id[]'; ?>" value="+3" /></td>
</tr>
<?php $i++; endforeach ; ?>
if i check the first checkbox i will get +1, the second checkbox i will get +2
my goal is to join the input from every checked checkbox and save to database based on id
and this is my code on model to join the value of checkbox
$menu_id= $this->input->post('menu_id');
$menu_idc = '';
$count = count($menu_id);
$i=0;
foreach($menu_id as $e){
if($i < $count -1)
{
$menu_idc .= $e.'';
echo $i ;
}
else{
$menu_idc .= $e.'+';
}
$i++;
}
var_dump($menu_idc);
die;
from example if i check this checkbox
id menu +1 +2 +3
1 bla_1 [v] [v] [v]
2 bla_2 [] [v] []
3 bla_3 [] [] [v]
with code i write i will get +1+2+3+2+3+ (+1+2+3 from row 1, +2 from row 2, +3 from row 3)
what i want is to get is value from every row and save to table on database
+1+2+3+ save into database
+2+ save into database
+3+ save into database
Database
id | isi |
1 | +1+2+3+ |
2 | +2+ |
3 | +3+ |
i think i must loop the code on my model but i dont know what code i have to write

What you need is a 2-dimensional array. The first dimension is for the row and the second one is for the columns.
First change your markup a bit to make the submitted values 2-dimensional:
<?php $i=1; foreach ($test as $row) : ?>
<tr>
<td><input type='hidden' name="menu[<?php echo $i ?>][id]" value="<?php echo $row->menu_id ?>" /></td>
<td><input type="text" name="menu[<?php echo $i ?>][menu]" value="<?php echo $row->menu_nama ?>" disabled <td>
<td><input type="checkbox" name="menu[<?php echo $i ?>][plus][]" value="+1" /></td>
<td><input type="checkbox" name="menu[<?php echo $i ?>][plus][]" value="+2" /></td>
<td><input type="checkbox" name="menu[<?php echo $i ?>][plus][]" value="+3" /></td>
</tr>
<?php $i++; endforeach ; ?>
This code should work fine:
$menus = $this->input->post('menu');
foreach ($menus as $menu)
{
$id = $menu['id'];
$name = $menu['name'];
$menu_ids = "";
if (is_array($menu['plus']))
{
$menu_ids = join('', $menu['plus'])).'+';
}
// here you can save it now by executing a sql update or whatever
}

You need a 2-dimensional array, the first dimension is the row, the second dimension is the checkboxes. In the form, you should have:
<td><input type="checkbox" name="<?php echo 'menu_id['.$row->menu_id.'][]'; ?>" value="+1" /></td>
<td><input type="checkbox" name="<?php echo 'menu_id['.$row->menu_id.'][]'; ?>" value="+2" /></td>
<td><input type="checkbox" name="<?php echo 'menu_id['.$row->menu_id.'][]'; ?>" value="+3" /></td>
Then in your processing script, you can do:
foreach ($_REQUEST['id'] as $id)
$isi[$id] = implode('', $menu_id[$id]);

Related

How to save textbox values entered in each row of a dynamic table

I have a dynamic table with 4 textboxes qty, price, discount and subtotal in each row. How to get an array with each values entered in each textbox in each row in $_POST? Like this for example:
[0]=> {
["Price"]=>10
["Qty"]=>5
["Discount"]=>1
["Subtotal"]=>49
}
[1]=> {
["Price"]=>5
["Qty"]=>10
["Discount"]=>2
["Subtotal"]=>48
}
This is my code:
<?php
while($iArticles < count($listeArticlePourUnDossier))
{
?>
<tr>
<td><?php echo ($listeArticle[$iArticles]['name']); ?></td>
<td><input type="text" name="Price[]" id="Price"/></td>
<td><input type="text" name="Qty[]" id="Qty" /></td>
<td><input type="text" name="Discount[]" id="Discount" /></td>
<td><input type="text" name="Subtotal[]" id="Subtotal" /></td>
</tr>
<?php
$iArticles++;
}
?>
Thank you
Not 100% sure I grasped the true nature of the question and the following has not been tested but will, I hope, be of use - there is no sanity / validity checking of supplied POST data here though
$prices=$_POST['Price'];
$qtys=$_POST['Qty'];
$discounts=$_POST['Discount'];
$subs=$_POST['Subtotal'];
$data=[];
foreach( $prices as $index => $price ){
$data[]=[
'price' => $price,
'qty' => $qtys[ $index ],
'discount' => $discounts[ $index ],
'subtotal' => $subs[ $index ]
];
}
printf( '<pre>%s</pre>', print_r( $data, true ) );
Make each HTML name an array with an index.
<?php
$x=0;
while($iArticles < count($listeArticlePourUnDossier))
{
$x++;
?>
<tr>
<td><?php echo ($listeArticle[$iArticles]['name']); ?></td>
<td>
<input type="text" name="Price[<?php echo $x; ?>]" id="Price_<?php echo $x; ?>"/>
<input type="text" name="Qty[<?php echo $x; ?>]" id="Qty_<?php echo $x; ?>" />
<input type="text" name="Discount[<?php echo $x; ?>]" id="Discount_<?php echo $x; ?>" />
<input type="text" name="Subtotal[<?php echo $x; ?>]" id="Subtotal_<?php echo $x; ?>" />
</td>
</tr>
<?php
$iArticles++;
}
?>

( PHP /JQuery?) Get the table row value when the checkbox is checked

It's a table, each row consists a checkbox, when it's checked, would like to get the respective td values and echo out. Here im using the if statement, but it doesn't seems to work.
And iam using php here, is using jquery a way out, can jquery work with php
code, so could i send those checked table row values back to serve? Any thoughts? Thank you.
<form>
<table>
<tr>
<?php
$specific = [];
while($row = mysqli_fetch_array( $result ,MYSQL_ASSOC)) {?>
<td><input type="checkbox" name="p[]" value="<?php echo $row['id']; ?>">
</td>
<td><input type="text" name="patientid[]"
style="border: none" value="<?php echo $row['patientid'] ?>"></td>
<td>
<textarea name="msg" style="border: none" class='msg'>
<?php echo $row['message'];} ?> </textarea>
</td>
<td><input class="phone" type="text" value="<?php echo
$row['telMobile'] ?>"></td>
check whether table row(s) are checked
<?php if(!isset($_GET['p'])){
$specific[] = [
"phone" => $row["telMobile"],
"message" =>$row["message"],
];}
}
$result = json_encode($specific,JSON_UNESCAPED_UNICODE);
echo $result;
echo "</tr>";
echo "</table>";
echo "</form>";?>
The desired result for $result is to show only the data of the table row(s) that are checked.
[{"phone":"123456","message":"test"},
{"phone":"789456","message":"testing"}]
Change your HTML code as below:
<td><input type="text" name="patientid[<?php echo $row['id']; ?>]"
style="border: none" value="<?php echo $row['patientid'] ?>"></td>
<td>
<textarea name="msg[<?php echo $row['id']; ?>]" style="border: none" class='msg'>
<?php echo $row['message'];} ?> </textarea>
</td>
<td><input name="phone[<?php echo $row['id']; ?>]" class="phone" type="text" value="<?php echo
$row['telMobile'] ?>"></td>
I have added <?php echo $row['id']; ?> in the input control name.
Change your PHP code as below:
foreach($_GET["p"] as $id) {
$specific[] = [
"phone" => $_GET["phone"][$id],
"message" => $_GET["msg"][$id],
];
}

PHP Variable changes its own value on equal loops

I have a variable putting out the coordinates of a address. I am printing the coordinates before the name to test at the moment. On odd number loops (it is in a foreach loop) it works fine, putting the variable in the data-latLng attribute. While on Even number loops it gives out different values - not coordinates. values like: 2 and ..
Here is what I mean:
An odd numbered loop would print this out:
Meanwhile on an even loop number, the data-latLng attribute puts out different values:
Here is the code:
$area_lat_long = isset($area_lat_long[$mapCounter])?$area_lat_long[$mapCounter]:"-26.2041028, 28.047305100000017";
echo $area_lat_long;
echo '<strong>area: '. $streetAdd[$count] .' <a class="glyphicon glyphicon-new-window" type="button" data-toggle="modal" data-target="#mapModal" data-latLng="'. $area_lat_long .'" style="cursor:pointer;"></a><br>';
$mapCounter++;
The PHP code runs above the table code, the code above gives the line of the coordinates and then the area.
As you can see, the $area_lat_long gives coordinates before every area, but when using the EXACT same variable for the data-latLng it changes on even loops?
Edit
To the guys who wanted the whole loop in the comments:
foreach ($streetAdd as $key){
print_r($area_lat_long);
//LAT LONG
$area_lat_long = isset($area_lat_long[$count])?$area_lat_long[$count]:"-26.2041028, 28.047305100000017";
echo $area_lat_long;
echo '<strong>area: '. $streetAdd[$count] .' <a class="glyphicon glyphicon-new-window" type="button" data-toggle="modal" data-target="#mapModal" data-latLng="'. $area_lat_long .'" style="cursor:pointer;"></a><br>';
$mapCounter++;?>
<input type="hidden" id="street_address" name="street_address[<?php echo $count; ?>]" value="<?php echo $streetAdd[$count];?>">
<table class="table table-striped">
<thead>
<tr>
<th>Media Type</th>
<th>Quantity Required</th>
<th>Average Asset Price</th>
<th><!-- Remaining Total --></th>
<th>More Options</th>
</tr>
</thead>
<tbody class="assetCounter">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php
$j = 0;
$total_used = 0;
$total_bal = isset($budget)?$budget:0;
$qty = 1;
$i = 0;
foreach ($my_categories as $key) { //loop thru chosen media types
foreach ((array)$key as $data) {
// print_r($data);
//check valid description
$j++;
$data_description = isset($data->mec_description)?$data->mec_description:'';
$latitude_longitude = explode(",",$area_lat_long); //print_r($latitude_longitude);
$latitude = $latitude_longitude[0];
$longitude = isset($latitude_longitude[1])?$latitude_longitude[1]:$latitude;
//pricing
$min_price = isset($data->asg_min_price)?$data->asg_min_price:0;
$max_price = isset($data->asg_max_price)?$data->asg_max_price:0;
$average_p = ($min_price + $max_price)/2;
$total_used += $average_p;
$total_bal -= $average_p;
if($total_bal < 0){
$total_bal = 0;
}
if($average_p == 0){
$title = "Pricing information not yet available from Media Owners";
} else {
$title = "NOTE: These are just estimates/guidelines, latest pricing information will be received from Media Owners quotations";
}
?>
<tr class="asset_<? echo $counterForAsset; ?>">
<td><?php
echo strtoupper($mec_stuff[$i]);
?>
<input type="hidden" id="media_category" name="mec_id[]" value="<?php
foreach($mec_stuff as $ms) {
echo $ms . ',';
}
?>">
<input type="hidden" id="media_category" name="media_category[]" value="<?php echo $data_description; ?>"></input></td>
<td><input type="text" class="form-control q_asset_<? echo $counterForAsset; ?> med_quantity" name="med_quantity[]" id="med_quantity" placeholder="Quantity Required" value="1"/></td>
<td><input type="text" readonly="true" name="avg_total[]" id="asset_<? echo $counterForAsset; ?>" class="form-control avg_asset_<? echo $counterForAsset; ?>" value="<?php echo number_format($total_bal,2); ?>" title="<?php echo $title;?>"/></td>
<!-- <td><input type="text" readonly="true" name="avg_total[]" id="avg_total--><?php //echo $j; ?><!--" class="form-control asset_--><?// echo $i; ?><!--" value="--><?php //echo number_format($total_bal,2); ?><!--" title="--><?php //echo $title;?><!--"/></td>-->
<td><input type="text" readonly="true" name="rem_total[]" id="asset_<? echo $counterForAsset; ?>" class="form-control rem_asset_<? echo $counterForAsset; ?>" value="<?php echo number_format($total_bal,2); ?>"/></td>
<!-- <td><input type="text" readonly="true" name="rem_total[]" id="rem_total--><?php //echo $j; ?><!--" class="form-control --><?// echo $i; ?><!-- asset_--><?// echo $i; ?><!--" value="--><?php //echo number_format($total_bal,2); ?><!--"/></td>-->
<td><?php echo "<a class='js-fire-modal btn btn-info' type='button' data-toggle='modal' data-mecid='$mec_stuff[$i]' href='#' name='size_button' onclick=\"sizeModal2(1, $j, '$latitude','$longitude','$description')\">>>></a>";?></td>
</tr>
<tr>
<td></td>
<td colspan="4" id="<?php echo $j; ?>"></td>
</tr>
<?php $i ++; $counterForAsset++; }
}?>
<tr>
<td> </td>
<td> <input type="hidden" id="hidSubtotal<?php echo $j;?>" value="<?php echo number_format($total_used,2); ?>"></td>
<td> Subtotal</td>
<td> <span id="lblSubtotal<?php echo $j; ?>"><?php echo number_format($total_used,2); ?></span> </td>
</tr>
</tbody>
</table>
<?php $count++;
}
foreach($a as $b) {
$x = isset($x[$c]) ? $x[$c] : "foo7";
echo $x;
}
Let us "run" that piece of code, assuming
$x = array('c' => 'lat,lng');
before the loop.
So loop #1 prints 'lat,lng'.
Loop #2 checks if isset('lat,lng'[$c]), evaluates to false, so $x will be 'foo'.
'foo' will be printed.
Loop #3 does the same as #2, but checks if isset('foo'[$c]), again evaluating to false.
Again 'foo' will be printed.
That's the reason.
I don't know what else you are doing outside that loop and most of the code seems to do nothing or nothing intended really.

Send multiple values with checkbox

I have a form and this form contains this table:
<?php foreach($resultTable as $key => $value)
{
?>
<table>
<tr>
<td><input type = "checkbox" name="idPriv[]" id="idPriv" onclick="evaluateIT(this)" data-related-item="adminPanelShow" value ="<?php echo $value["id"]?>" />
<input name="rowID[]" id="rowID[]" class="adminPanel" hidden="hidden" type="text" value="<?php echo $value["id"]?>"/></td>
<td><input type="text" name="userName[]" id="userName" class="adminPanel" value="<?php echo $value["userName"]?>"/></td>
<td><input name="firstName[]" type="text" id="firstName" class="adminPanel" value="<?php echo $value["firstName"]?>"/></td>
</tr>
<?php } ?>
</table>
When I'm selecting the wanted checkboxes and submitting the form, I want to use only the checkboxes that I checked. That means, the idPriv[] array returns only the checkboxes that was pressed, BUT the other arrays (userName[], firstName[]) send all of the data for all the rows.
How do I extract the data from those arrays only (and disregard the rows that wasn't checked)?
To check if the checkboxes are checked, parse them as such:
foreach($resultTable as $key => $value)
{
if($value==="on")
{
// checked checkbox has a value of "on"
// triple = sign means value is exactly "on"
}
}
Connect each userName, firstName field with checkbox value:
foreach($resultTable as $key => $value)
{?>
<table>
<tr>
<td><input type = "checkbox" name="idPriv[]" id="idPriv" onclick="evaluateIT(this)" data-related-item="adminPanelShow" value ="<?php echo $value["id"]?>" />
<input name="rowID[]" id="rowID[]" class="adminPanel" hidden="hidden" type="text" value="<?php echo $value["id"]?>"/></td>
<td><input type="text" name="userName[<?php echo $value["id"]?>]" id="userName" class="adminPanel" value="<?php echo $value["userName"]?>"/></td>
^--- here
<td><input name="firstName[<?php echo $value["id"]?>]" type="text" id="firstName" class="adminPanel" value="<?php echo $value["firstName"]?>"/></td>
^--- here
</tr>
}
</table>
After that in your script you can do something like that:
foreach ($_POST[`idPriv`] as $id) {
$firstName = $_POST['firstName'][$id];
$userName = $_POST['userName'][$id];
// ...
}

saving data from an array without submitting any form php

I'm tryng to save an array so I have the following code:
<?php
$sql = "SELECT * FROM scenarii where code_s='".mysql_real_escape_string($_POST['code_s'])."'";
$qry = mysql_query($sql) or die(__LINE__.mysql_error().$sql);
$i = -1; // index des enregistrements
?>
<table cellpadding="5" cellspacing="5">
<tr>
<td><strong>CODE SCENARIO</strong></td>
<td><strong>LIBELLE</strong></td>
<td><strong>ACTION</strong></td>
<td><strong>DESCRIPTION</strong></td>
<td><strong>DATE</strong></td>
</tr>
<form action="<?php echo (isset($_POST['go'])) ? 'go.php' : '#'; ?>" method="post">
<input type="hidden" name="liasse" value="<?php echo $_POST['liasse']; ?>"/>
<input type="hidden" name="n_doss" value="<?php echo $_POST['n_doss']; ?>"/>
<input type="hidden" name="qualite" value="<?php echo $_POST['qualite']; ?>"/>
<?php while($row = mysql_fetch_assoc($qry)): ?>
<tr>
<td><input name="data[<?php echo ++$i; ?>][code_s]" type="text" value="<?php echo $row['code_s'];?>" size="10"></td>
<td><input name="data[<?php echo $i; ?>][titre]" type="text" value="<?php echo $row['titre']; ?>" size="45"></td>
<td><input name="data[<?php echo $i; ?>][action]" type="text" value="<?php echo $row['action']; ?>" size="15"></td>
<td><input name="data[<?php echo $i; ?>][libelle]" type="text" value="<?php echo $row['libelle']; ?>" size="55"></td>
<td><input type="text" name="data[<?php echo $i; ?>][date]" value="<?php echo $get_date($row['jour']) ; ?>" size="12"></td>
</tr>
<?php endwhile; ?>
And in order to save this I have this code:
if (isset($_POST['liasse'])) {
$value = $_POST['data'] ;
foreach($value as $key => $array)
{
$sql = 'INSERT INTO agenda SET
liasse = "'.mysql_real_escape_string($_POST['liasse']).'",
code_s = "'.mysql_real_escape_string($array['code_s']).'",
date_action = "'.date('Y-m-d',strtotime($array['date'])).'",
libelle = "'.mysql_real_escape_string($array['titre']).'",
action = "'.mysql_real_escape_string($array['action']).'",
description = "'.mysql_real_escape_string($array['libelle']).'",
n_doss = "'.mysql_real_escape_string($_POST['n_doss']).'",
qualite = "'.mysql_real_escape_string($_POST['qualite']).'"
';
mysql_query($sql) or die(__LINE__.mysql_error().$sql);
}
But I'm really lost,
In fact I use a form for that, now I would like to submit all of this data but without any form, directly when I have the first while I would like to save it.
The thing is that I'm lost because I can not call any var like that data[][code_s].
So I do not know how to save this. I would like to save it in background, and not to display that something has been saved.
Receive all my Utmost Respect
kind regards,
SP.
Wrap the code od the lower code block into a function and hand over the value array as argument:
function storeValues ($data) {
foreach($data as $key => $val)
{
$catalog=sprintf("%s='%s'",$key,$val);
$sql = sprintf('INSERT INTO agenda SET %s', implode(',',$catalog));
mysql_query($sql) or die(__LINE__.mysql_error().$sql);
} // foreach
} // function storeValues
You call this function when you want to save the values. So after retrieving them from the database. You call it for each row you retrieve and hand over the values like that:
storeValues ($row);
This will store one row of values at a time. Obviously this can be optimized to use a multiple insert. But let's take one step after another...

Categories