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.
Related
I try to get the data from database using foreach loop and display them in column way, at the moment i receive them as it appears on this
but i need that it appears like this way
| Founders Circle | Global Pool | Universal Pool | Infinity Pool | Regional Pool |
|78156 -and input- |1021673-input | 5000000 - input | 56823 - input | 0 and input |
<?php
foreach( $calculations as $calculation ) {
?>
<table>
<tr>
<th>
<?php echo $calculation['Calculation']['poolname']; ?>
</th>
</tr>
<tr>
<td>
<div class="input text" id="pool_calc">
<?php echo $calculation['Calculation']['total_units']; ?>
<input name="own_pools" type="text" value="" id="own_pools" maxlength="3" size="4" >
</div>
</td>
</tr>
<?php
}
?>
</table>
what is wrong or how can i fix it?
There are more ways, the easiest one for understanding for you is to use two same foreach loops.
<table>
<tr>
<?php
foreach( $calculations as $calculation ) {
// All TH in the first row
?>
<th>
<?php echo $calculation['Calculation']['poolname']; ?>
</th>
<?php
}
?>
</tr>
<tr>
<?php
foreach( $calculations as $calculation ) {
// All TD in the second row
?>
<td>
<div class="input text" id="pool_calc">
<?php echo $calculation['Calculation']['total_units']; ?>
<input name="own_pools" type="text" value="" id="own_pools" maxlength="3" size="4" >
</div>
</td>
<?php
}
?>
</tr>
</table>
In your code in the Question you create for each record new table with 2 rows (you had 5 tables in total).
The basic idea is to move <table> outside the loop.
Updated code doing the some, without duplicating foreach loop (saving TDs in variable and echo later).
<table>
<tr>
<?php
$tds = '';
foreach( $calculations as $calculation ) {
// All TH in the first row
?>
<th>
<?php echo $calculation['Calculation']['poolname']; ?>
</th>
<?php
// create TDs code
$tds .= '
<td>
<div class="input text" id="pool_calc">
' . $calculation['Calculation']['total_units'] . '
<input name="own_pools" type="text" value="" id="own_pools" maxlength="3" size="4" >
</div>
</td>
';
}
?>
</tr>
<tr>
<?php
echo $tds;
// echo TDs in the second row
?>
</tr>
</table>
Hello I am beginner here. I have a record like this in my SQL Table
id name_id score
1 N_1 98
2 N_3 78
3 n_3 68
I have a HTML and PHP set of code that display a table with an input fields next to each of its ID's and Name which looks like
CONSIDER [ ] AS INPUT FIELDS
ID NAME SCORE
N_4 James []
N_5 Kit []
N_6 Chino []
When I put some scores into it just like
ID NAME SCORE
N_4 James [98]
N_5 Kit [76]
N_6 Chino [81]
My SQL table should look like this
id name_id score
1 N_1 98
2 N_2 78
3 N_3 68
4 N_4 98
5 N_5 76
6 N_6 81
But instead of inserting 3 rows of data in my SQL Table it just insert as one, just look like this
id name_id score
1 N_1 98
2 N_2 78
3 N_3 68
4 N_4 98
What should I do? Here is some of my code
<?php $sql = "SELECT l_name, f_name, m_name, sid FROM tbl_student WHERE section='".$_POST['section']."';"; ?>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<?php $result = mysqli_query($db, $sql);
while ($resultset = mysqli_fetch_assoc($result)){ ?>
<tr>
<form method="post">
<td><?php echo $resultset ['sid']; ?></td>
<td style="text-transform:capitalize;"><?php echo $resultset ['l_name']; echo ", "; echo $resultset ['f_name']; echo " "; echo $resultset ['m_name'];?></td>
<td><input type="text" style="width:50px;" name="grade"></td>
<input type="hidden" name="id" value="<?php echo $resultset ['sid']; ?>">
</tr>
<?php } ?>
</tbody>
</table>
<button class="pull-right btn btn-info" type="submit" name="submit_tbl_grade">SAVE</button>
</form>
<?php } ?>
<?php if(isset($_POST['submit_tbl_grade'])){
$name = $_POST['grade'];
$id = $_POST['id'];
$record = "INSERT INTO tbl_grade(stud_id,component_value) VALUES ($id,$name)";
mysqli_query($db,$record);
Change your input tags like below.
<input type="text" style="width:50px;" name="grade[]">
<input type="hidden" name="id[]" value="<?php echo $resultset ['sid']; ?>">
Then you can access the values like below,
$name = $_POST['id'][0]
$id = $_POST['grade'][0]
Using a loop you can access the values and insert them to DB.
I am learning PHP and trying to make a simple cart/processing script.
I have created the item cart fine, but I am having trouble displaying information in my receipt when a user commits to buying the item(s) in their cart.
To save space/time I have omitted my item lists and the generation of the cart, they can be found here if you need it.
Here is the PHP that posts the data to my checkout.php script
cart.php (Updated to reflect change)
<?php
session_start(); ?>
<form name="cart" id="cart" action="checkout.php" target='_blank'
method='post'>
<h1>Your Cart:</h1>
<table>
<tr>
<td><span class='title'>ID</span></td>
<td><span class='title'>Product</span></td>
<td><span class='title'>Price</span></td>
</tr>
<?php
// Set a default total
$total = 0;
foreach ( $_SESSION['cart'] as $cartid ) {
?>
<tr>
<td width="20%">
<?php echo $cartid; ?> <input type="hidden" name="id[]"
value="<?php echo $cartid; ?>">
</td>
<td width="100%">
<?php echo $title?>
<input type="hidden" name="title[]" value="<?php echo $title; ?>">
</td>
<td width="100%">$<?php echo $price;?>
<input type="hidden" name="prices[]" value="<?php echo $price; ?>">
</td>
</tr>
<?php
$total += $price;
} // end foreach
?>
<tr>
<td>Total</td>
<td></td>
<td>$<?php echo $total; ?></td>
</tr>
</table>
<input type="submit" value="Buy" class="submit-button" />
</form>
checkout.php (Updated to reflect change)
<table>
<tr>
<th>ID</th>
<th>Product</th>
<th>Price</th>
</tr>
<?php
foreach($_POST['ids'] as $id) {
echo "
<tr>
<td>$id</td>
<td>$_POST['titles'][$id]</td>
<td>$_POST['prices'][$id]</td>
</tr>
";
}
?>
<tr>
<td>Total</td>
<td></td>
<td>$</td>
</tr>
</table>
I cannot seem to get the foreach loop to read the item id, title, or price. I can see the array is being passed using print_r($_POST); but it is indexing each item as a new array item e.g:
Array
(
[checkout] => Array
(
[0] => A123
[1] => Item1
[2] => 1000
[3] => Z999
[4] => Item999
[5] => 9999
)
)
How can I post the information in a more meaningful way i.e. associated array. Then use that associated array to display information in a table like format?
Expected output
<table>
<tr>
<th>ID</th>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>A123</td>
<td>Item1</td>
<td>$1000</td>
</tr>
<tr>
<td>Z999</td>
<td>Item999</td>
<td>$9999</td>
</tr>
<tr>
<td>Total</td>
<td></td>
<td>$10999</td>
</tr>
</table>
N.B: This is just a learning exercise so array sanitizing not required, and no SQL.
Edit: Updated to reflect #Obsidian Age recommendations, getting parse error now
Your items all have the same name attribute in HTML:
<input type="hidden" name="checkout[]">
You would need three different named variables for submission, with one of them being the ID of the particular transaction:
<input type="hidden" name="ids[]">
<input type="hidden" name="titles[]">
<input type="hidden" name="prices[]">
Then you can loop through each item and add it to a corresponding array:
$titles = [];
$prices = [];
foreach($_POST['ids'] as $id) {
array_push($titles, $_POST['titles'][$id]);
array_push($prices, $_POST['prices'][$id]);
}
Or output it directly:
foreach($_POST['ids'] as $id) {
$title = $_POST['titles'][$id];
$price = $_POST['prices'][$id];
echo "
<tr>
<td>$id</td>
<td>$title<td>
<td>$price</td>
</tr>
";
}
Hope this helps! :)
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.
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 />';
}