Checkbox with Result from Database in PHP - php

I have a record fetch from database based on a dropdown selection.The result is shown as a table, in which the user is expected to tick his choice.After the selection,the user clicks a button which will automatically add his selection to a table.Now the issue is: the id that is fetched for each item changes when the button is clicked by turning it to ascending number.see image below:
For instance, in the table below, id 773,774,777,895 and 901 are selected.When Add to Float Button is cliked, the Id now becomes: 773,774,775,776,777(arranged ascending). See code below:
for Displaying Table
<table>
<tr>
<td><input type="text" value="<?php echo $r['item_code'];?>" name="itmcode[]" readonly="readonly"/></td>
<td><?php echo $r['description'];?></td>
<td><?php echo $r['qty'];?></td>
<td><?php echo $r['price_per_qty'];?>
<td><input type="text" value="<?php echo $r['total_value'];?>" name="tvalue[]" readonly="readonly" /></td>
<td><?php echo $r['preferred_supplier'];?></td>
<td><input type="checkbox" name="chkbx[]" value="<?php echo $r['id'];?>">
<input type="hidden" name="gid[]" value="<?php echo $r['id'];?>">
</tr>
</table>
Processing Script:
<?php
if(array_key_exists('chkbx', $_POST)&&(!empty($_POST['chkbx']))&&(isset($_POST['floatBtn']))){
foreach($_POST['chkbx'] as $rec=>$value)
{
$itm = $_POST['itmcode'][$rec];
$tval = $_POST['tvalue'][$rec];
$t = $_POST['gid'][$rec];
$apno =$_POST['aNo'];
$fno = $_POST['fno'];
echo "itm:".$itm." tval: ".$tval." t:".$t." appno:".$apno."fno:".$fno."<br/>";
}
}
?>
How can I correct this, so that it can display the correct id when the button is clicked after selecting.

Change your code like this
<table>
<tr>
<td><input type="text" value="<?php echo $r['item_code'];?>" name="itmcode[]" readonly="readonly"/></td>
<td><?php echo $r['description'];?></td>
<td><?php echo $r['qty'];?></td>
<td><?php echo $r['price_per_qty'];?>
<td><input type="text" value="<?php echo $r['total_value'];?>" name="tvalue[]" readonly="readonly" /></td>
<td><?php echo $r['preferred_supplier'];?></td>
<td><input type="checkbox" name="chkbx[]" value="<?php echo $r['id'];?>">
//change gid[] to gid[<?php echo $r['id'];?>]
<input type="hidden" name="gid[<?php echo $r['id'];?>]" value="<?php echo $r['id'];?>">
</td>
</tr>
</table>
in processing
<?php
if(array_key_exists('chkbx', $_POST)&&(!empty($_POST['chkbx']))&& (isset($_POST['floatBtn']))){
foreach($_POST['chkbx'] as $rec=>$value)
{
$itm = $_POST['itmcode'][$rec];
$tval = $_POST['tvalue'][$rec];
$t = $_POST['gid'][$value]; //--> changed from $_POST['gid'][$rec] to $_POST['gid'][$value]
$apno =$_POST['aNo'];
$fno = $_POST['fno'];
echo "itm:".$itm." tval: ".$tval." t:".$t." appno:".$apno."fno:".$fno."<br/>";
}
}
?>
The issue when you post the data with the checkbox checked, you get an array like this
Array
(
[itmcode] => Array
(
[0] => 1"
[1] => 1"
[2] => 1"
)
[tvalue] => Array
(
[0] => 5
[1] => 5
[2] => 5
)
[chkbx] => Array
(
[0] => 1
)
[gid] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
so when looping the $_POST['chkbx'], the value for
`$_POST['gid'][$rec] always loops with the keys of $_POST['chkbx'] which is 0,1,2 etc always. So you get values of $_POST['gid'][0], $_POST['gid'][1],$_POST['gid'][2], etc which is 773, 774, 775 respectively.

Related

Store Dynamic Radio Option Value Array in MySQL using PDO

In a quiz app, I am generating Radio options for each question dynamically from database. I need to store the chosen answer of the questions the user submitted in a database table. I want to know which user picked which answer for which question.
Here is my form:
<form id="question" class="" action="quiz_ans.php" method="post">
<table id="quiz-question" align="center" class="row-border compact order-column stripe">
<input class="form-control" type="hidden" name="NumberofQuestions" id="NumberofQuestions" value="<?php echo $NumberofQuestions; ?>">
<thead>
<?php
if($QuizQuestions) {
$i=1;
foreach($QuizQuestions as $row):
?>
<tr>
<th><?php echo $i; ?>. <?php echo $row->Question; ?>
<br>
<?php if(isset($row->Screenshot)) { ?>
<img src="<?php echo htmlspecialchars($row->Screenshot); ?>" alt="test" height="300" width="980">
<?php } ?>
</th>
</tr>
</thead>
<tbody>
<?php if(isset($row->Option1)) { ?>
<tr class="info">
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="0"><?php echo $row->Option1; ?></td>
</tr>
<?php } ?>
<?php if(isset($row->Option2)) { ?>
<tr class="info">
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="1"> <?php echo $row->Option2; ?></td>
</tr>
<?php } ?>
<?php if(isset($row->Option3)) { ?>
<tr>
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="2"> <?php echo $row->Option3; ?></td>
</tr>
<?php } ?>
<?php if(isset($row->Option4)) { ?>
<tr>
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="3"><?php echo $row->Option4; ?></td>
</tr>
<?php } ?>
<tr>
<td><label for="AnswerReason">Why?</label><input class="form-control" type="text" name="AnswerReason[]" id="AnswerReason" value=""></td>
</tr>
<?php if(isset($row->Id)) { ?>
<tr>
<td><input class="form-control" type="hidden" name="QuestionId[]" id="QuestionId" value="<?php echo $row->Id; ?>"></td>
</tr>
<?php } ?>
</tbody>
<?php
$i++;
endforeach;
}
?>
</table>
<br>
<input type="submit" name="submit" value="Submit" class="btn btn-success">
</form>
This is how I tried to store the data in database table:
$NumberofQuestions = $_POST['NumberofQuestions'];
for ($i=0; $i<$NumberofQuestions; $i++)
{
$sql = "INSERT INTO tblquizresponse (QuestionId, AnswerId, AnswerReason, UserId, SubmittedAt) VALUES (' ".$_POST['QuestionId'] [$i]." ',
' ".$_POST['AnswerId'] [$i]." ', ' ".$_POST['AnswerReason'] [$i]." ', ' ".$UserId." ', ' ".$SubmittedAt." ')";
$stmt = $pdo->prepare($sql);
$stmt->execute();
}
But I do not get the AnswerId stored in database. Here is the array I get if the form is submitted:
Array
(
[NumberofQuestions] => 5
[AnswerId] => Array
(
[16] => 0
[17] => 1
[18] => 2
[74] => 3
[75] => 0
)
[AnswerReason] => Array
(
[0] => Test answer one reason.
[1] => Test answer two reason.
[2] => Test answer three reason.
[3] => Test answer four reason.
[4] => Test answer five reason.
)
[QuestionId] => Array
(
[0] => 16
[1] => 17
[2] => 18
[3] => 74
[4] => 75
)
[submit] => Submit
)
Here is the data stored in table after submit:
Id QuestionId AnswerId AnswerReason UserId SubmittedAt
1 16 0 Test answer one reason. xxxxxxxx 2020-02-26 12:38:53
2 17 0 Test answer two reason. xxxxxxxx 2020-02-26 12:38:53
3 18 0 Test answer three reason. xxxxxxxx 2020-02-26 12:38:53
4 74 0 Test answer four reason. xxxxxxxx 2020-02-26 12:38:53
5 75 0 Test answer five reason. xxxxxxxx 2020-02-26 12:38:53
How do I get the AnswerId stored in the database as well? Any help would be much appreciated.

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 save data into two rows at a time in database?

I have a form like this
<form class="product-data" action="">
<table>
<tr class="data-row">
<td>
<input type="number" name="finance[a][source_unit]" >
</td>
<td >
<input type="number" name="finance[a][target_unit]">
</td>
<td>
<input type="number" name="finance[a][client_price]">
</td>
<td>
<input type="number" name="finance[a][client_salary]" >
</td>
</tr>
<tr class="data-row">
<td>
<input type="number" name="finance[b][source_unit]" >
</td>
<td >
<input type="number" name="finance[b][target_unit]">
</td>
<td>
<input type="number" name="finance[b][client_price]">
</td>
<td>
<input type="number" name="finance[b][client_salary]" >
</td>
</tr>
</table>
</form>
here you can see I have two rows. One for a and another for b. Now I want to save them in the database with two rows. One for the a and another for b at a same time. When I am doing print_r(finance). with this code
$finances = $_POST['finance'];
print_r($finances);
Its showing me an array like this
Array
(
[a] => Array
(
[source_unit] => 3213
[target_unit] => 657654322343
[client_price] => 5435.00
[client_salary] => 897.00
)
[a] => Array
(
[source_units] => 67656565
[target_units] => 43243
[client_price] => 23432.00
[client_salary] => 6546.00
)
)
Now can someone tell me how to save them in each row. I have my database table is like this and the data should be saved like this
Id, product_type, source_unit, target_unit, client_price, lient_salary
1 A 3213 657654322343 5435 897
2 B 67656565 43243 23432 6546
I have two solutions for you. Once that is tailored for this scenario only:
$f = $_POST['finance'];
// insert first row
$query = "INSERT INTO `table` VALUES (NULL, 'A', {$f['a']['source_unit']}, {$f['a']['target_units']}, {$f['a']['client_price']}, {$f['a']['client_salary']})";
mysql_query($query);
// insert second row
$query = "INSERT INTO `table` VALUES (NULL, 'B', {$f['b']['source_unit']}, {$f['b']['target_units']}, {$f['b']['client_price']}, {$f['b']['client_salary']})";
mysql_query($query);
or if you have it more universal (for multiple rows):
$f = $_POST['finance'];
foreach($f as $key => $item) {
// assign key of the letter as value to insert
$letter = strtoupper($key);
// insert a row
$query = "INSERT INTO `table` VALUES (NULL, '{$letter}', {$item['source_unit']}, {$item['target_units']}, {$item['client_price']}, {$item['client_salary']})";
mysql_query($query);
}
loop thru your array and either insert or update accordingly.
foreach($finances as $key => $data)
{
//based on the $key if value exists in database update else insert
echo $key.'<br />';
echo $data['source_unit'].'<br />';
echo $data['target_unit'].'<br />';
echo '<hr />';
}

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

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

Categories