data not inerted correctly when going through a loop - php

$answersql = "INSERT INTO Penalty_Marks (PenaltyAnswer, PenaltyMarks, QuestionId)
VALUES (?, ?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
// Handle errors with prepare operation here
}
$c = count($_POST['incorrect']);
for($i = 0; $i < $c; $i++ )
{
$incorrect = $_POST['incorrect'][$i];
$answerMarks = $_POST['answerMarks'][$i];
$numQuestion = $_POST['numQuestion'][$i];
$insertanswer->bind_param('sii', $incorrect, $answerMarks, $numQuestion);
$insertanswer->execute();
}
The above insert is not inserting all the incorrect answers into the table, it is only inserting one incorrect answer per question. What am I doing wrong?
Below is the currect db table looks like:
PenaltyAnswerId PenaltyAnswer PenaltyMarks QuestionId
1 A 4 12
2 D 1 13
Below is what it should of been like:
PenaltyAnswerId PenaltyAnswer PenaltyMarks QuestionId
1 A 4 12
2 B 3 12
3 D 0 12
4 D 1 13
5 E 1 13
Below is form:
<form id="PenaltyMarks" action="insertpenaltymarks.php" method="post">
<table id='penaltytbl'>
<?php
foreach($ques_ans as $questionId => $inc_ans)
{
$q_row_span = count($inc_ans);
$row_count = 0;
$inc_ans = array_values($inc_ans);
?>
<tr class="questiontd">
<td>
<input type="hidden" name="numQuestion[]" value="<?php echo$questionId?>" />
</td>
<td>
<input type="hidden" class="hiddenincorrect" name="incorrect[]" value="<?php echo$inc_ans[$row_count];?>">
</td>
<td>
<input name="answerMarks[]" type="text" data-type="qmark" value='0' />
</td>
</tr>
<?php
//remaining incorrect answers in separate row (if any) follows here
if($row_count < $q_row_span - 1)
{
for($i=($row_count + 1); $i<$q_row_span; $i++) { ?>
<tr>
<td>
<input type="hidden" class="hiddenincorrect" name="incorrect[]" value="<?php echo$inc_ans[$i];?>">
</td>
<td class="answermarkstd">
<input name="answerMarks[]" type="text" data-type="qmark" value='0' />
</td>
</tr>
<?php
}
}
}
?>
</table>
<input id="submitBtn" name="submitPenalty" type="submit" value="Submit Marks" />
</form>
Below is jquery handling submit:
myClickHandler = function(e) {
if (confirm("Are you sure you want to Proceed?" + "\n")) {
$.ajax({
url: "insertpenaltymarks.php",
data: $("#PenaltyMarks").serialize(),
async: false,
type: "POST"
});
return true;
} else {
return false;
}
};
$('#PenaltyMarks').submit(myClickHandler);
});
UPDATE:
Question Table:
QuestionId (PK auto) (int 10)
QuestionNo (int 4)
QuestionContent (varchar 5000)
Penalty_Marks Table;
PenaltyAnswerId (PK auto) (int 10)
PenaltyAnswer (Varchar 5)
PenaltyMarks (int 3)
QuestionId (FK) (int 10) Reference to QuestionId in Question Table

Updated
With your current code, you can var_dump and found that the $_POST['numQuestion'] array may contains a fewer member than the $_POST['incorrect'][$i] array. I have updated my code too.
<form id="PenaltyMarks" action="insertpenaltymarks.php" method="post">
<table id='penaltytbl'>
<?php
foreach($ques_ans as $questionId => $inc_ans)
{
$q_row_span = count($inc_ans);
$row_count = 0;
$inc_ans = array_values($inc_ans);
?>
<tr class="questiontd">
<td>
<input type="hidden" name="numQuestion[<?php echo $questionId; ?>]" value="<?php echo$questionId?>" />
</td>
<td>
<input type="hidden" class="hiddenincorrect" name="incorrect[<?php echo $questionId; ?>][]" value="<?php echo$inc_ans[$row_count];?>">
</td>
<td>
<input name="answerMarks[<?php echo $questionId; ?>][]" type="text" data-type="qmark" value='0' />
</td>
</tr>
<?php
//remaining incorrect answers in separate row (if any) follows here
if($row_count < $q_row_span - 1)
{
for($i=($row_count + 1); $i<$q_row_span; $i++) { ?>
<tr>
<td>
<input type="hidden" class="hiddenincorrect" name="incorrect[<?php echo $questionId; ?>][]" value="<?php echo $inc_ans[$i];?>">
</td>
<td class="answermarkstd">
<input name="answerMarks[<?php echo $questionId; ?>][]" type="text" data-type="qmark" value='0' />
</td>
</tr>
<?php
}
}
}
?>
</table>
<input id="submitBtn" name="submitPenalty" type="submit" value="Submit Marks" />
</form>
The insertion script should be changed too :)
foreach($_POST['incorrect'] as $questionId => $incorrectArray)
{
for($i = 0; $i < count($incorrectArray), $i++)
{
$incorrect = $_POST['incorrect'][$questionId][$i];
$answerMarks = $_POST['answerMarks'][$questionId][$i];
$numQuestion = $_POST['numQuestion'][$questionId];
$insertanswer->bind_param('sii', $incorrect, $answerMarks, $numQuestion);
$insertanswer->execute();
}
}

Related

Array Dublicates data in sql

This is the HTML code
<tr role="row" class="odd">
<td> <input type="text" value="" class="form-control" id="earn[]" name="earn[]">
<input type="hidden" value="123" class="form-control" name="eid[]">
</td>
</tr>
and here is my code
include "settings/config.php";
$empid= trim(strip_tags($_POST['eid']));
for($i = 0; $i < count($_POST['earn']); $i++)
{
$earnval = $_POST['eid'][$i];
if (empty(trim($earnval))) continue;
$updatepayrollearn=$conn->prepare("UPDATE `emp_ern_cart` SET earnings='$earnval' WHERE empid='$empid'");
$updatepayrollearn->execute();
echo 'Data Updated';
}
The problem is, this code submit same data, let say the input data are (A,B,C) then the code submit (C,C,C)

Insert data from while loop into a table with php

I'm creating a form using HTML and PHP. I have created a form which I want to submit and save that data in database.
I'm trying to submit a form with data that comes from a while loop. All input values are getting generated by while loop.
The code looks like this.
<table width="1348" border="0" class="table table-striped" >
<tr>
<td width="106"> </td>
<td width="332"><strong>Product Code</strong></td>
<td width="375"><strong>Product Name</strong></td>
<td width="211"><strong>QTY</strong></td>
</tr>
<?php
$i = 0;
$rowset = mysql_query("select * from product_detail where productID='".$data['productCode']."'");
while($stuff = mysql_fetch_array($rowset)){
?>
<tr>
<td><input type="text" name="code[<?php echo $i?>]" value="<?php enter code hereecho $stuff['code'];?>"/></td>
<td><input type="text" name="name[<?php echo $i?>]" value="<?php echo $stuff['name'];?>" size="50"/></td>
<td><input type="text" name="qty[<?php echo $i?>]" value="<?php echo $stuff['qty'];?>" size="10"/></td>
</tr>
<?php $i++; }?>
<tr id="last">
</table>
<input type="submit" name="save id="save" class="btn btn-primary btn-lg"/>
This is the code to add the data to database.
$code=$_POST['code'.$i];
$name=$_POST['name'.$i];
$qty=$_POST['qty'.$i];
$query = mysqli_query($con,"insert into stock(productCode, productName, qty) values ('".$code."', '".$name."','".$qty."')") or die(mysqli_error($con));
First, use prepared statement with bind_param as your script is totally exposed to sql injection.
Second, you can add input type hidden for the number of rows
<form action="" method="POST">
<table width="1348" border="0" class="table table-striped" >
<tr>
<td width="106"> </td>
<td width="332"><strong>Product Code</strong></td>
<td width="375"><strong>Product Name</strong></td>
<td width="211"><strong>QTY</strong></td>
</tr>
<?php
$data['productCode'] = "1"; // sample data
$stmt = $con->prepare("SELECT * FROM product_detail WHERE productID = ?");
$stmt->bind_param("i", $data['productCode']);
$stmt->execute();
$result = $stmt->get_result();
$i = 0;
while($stuff = $result->fetch_assoc()) {
?>
<tr>
<td></td>
<td><input type="text" name="code[<?php echo $i; ?>]" value="<?php echo $stuff['code'];?>"/></td>
<td><input type="text" name="name[<?php echo $i; ?>]" value="<?php echo $stuff['name']; ?>" size="50" /></td>
<td><input type="text" name="qty[<?php echo $i; ?>]" value="<?php echo $stuff['qty']; ?>" size="10" /></td>
</tr>
<?php
$i++;
}
?>
<input type="hidden" name="count" value="<?php echo $i; ?>" />
<tr id="last">
</table>
<input type="submit" name="save" id="save" class="btn btn-primary btn-lg"/>
</form>
post count with the form
<?php
if (isset($_POST['save'])) {
$count = $_POST['count'];
for ($i = 0; $i < $count; $i++) {
$code = $_POST['code'][$i]; // check empty and check if interger
$name = $_POST['name'][$i]; // check empty and strip tags
$qty = $_POST['qty'][$i]; // check empty and check if interger
$stmt = $con->prepare("INSERT INTO stock (productCode, productName, qty) VALUES (?, ?, ?)");
$stmt->bind_param("iss",$code,$name,$qty);
$stmt->execute();
}
}
?>
You may also want to check if post values are empty with other necessary validation before insert
Since the table is dynamically filled, you need to use an array as the name attribute
<table>
<tr>
<th>Name</th>
<th>Present</th>
<th>Excused</th>
<th>Unexcused</th>
<th>Ext</th>
</tr>
<?php
$query = "select * from TbCard";
$sql = mysqli_query($connect, $query);
$count = 0;
while ($data = mysqli_fetch_array($sql)) {
?>
<tr>
<td>
<input name="tableRow[<?php echo $count; ?>]['dataName']" id='name' type='text' value="<?php echo $data['Name'];?>" readonly style='border:none;width:350px'></input>
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Present"> Present
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Excused"> Excused
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Unexcused"> Unexcused
</td>
</tr>;
<?php
$count++;
}
?>
</table>
The php would be something like this, assuming that the data has values in it:
$tableRow = $_POST['tableRow'];
foreach($tableRow as $row){
/* here insert data from post */
echo $row['dataName'].' '.$row['status'].'<br/>';
}
To see the content of the array, use print_r($tableRow)
in this case i use a name tableRow

How to insert data in php/mysql in one save click?

I have table player_points with player_name, runs, sixes, match_no, fiftys, hundreds, point_scored.
I make form with above fields where i insert runs and sixes and calculate fiftys, hundreds and point_scored using runs & sixes, give extra 10 points for every sixex after 3 six.
Its works properly but when i insert runs and sixes and save it only shows calculation in fiftys, hundred and point-scored textbox not saved into database table. After i saved it second time its save into database. My code is like below:
<tr><td colspan="9"><hr style="border:1px #999 dashed;"></td></tr>
<tr>
<th>Player</th>
<th>Status</th>
<th>Runs</th>
<th>6's</th>
<th>50's</th>
<th>100's</th>
<th>TP</th>
<th>Action</th>
</tr>
<tr><td colspan="9"><hr style="border:1px #999 dashed;"></td></tr>
<?php
$classObj->getPlayerPointTable();
//$matchid = $_GET['mid'];
$condpl = "player_name='".$player1."' AND match_no = '".$matchid."'";
$resultpl = $classObj->selectSql($condpl);
//$recordcount = $classObj->getAffectedRows($result);
$rowpl = $classObj->fetchData($resultpl);
foreach($rowpl as $rowspl)
{
$Status1 = $rowspl['status'];
$runs1 = $rowspl['run_scored'];
$sixes1 = $rowspl['sixs'];
$fifty1 = $rowspl['fifty'];
$hundred1 = $rowspl['hundred'];
$total_score1 = $rowspl['Total_Score'];
$total_points1 = $rowspl['point_scored'];
$firstPoint1 = $rowspl['FirstPoint'];
$allocation1 = $rowspl['allocation'];
}
?>
<?php
$bonus1 = 10;
$bonus2 = 20;
$bonus3 = 25;
$bonus4 = 50;
/*condition for fifty 0 & 1 start */
if ($runs1 >= 50 && $runs1 <= 99 || $runs1 >= 150 && $runs1 <= 199 || $runs1 >= 250 && $runs1 <= 299) {
$fifty1 = 1;
} else {
$fifty1 = 0;
}
if ($runs1 >= 50 && $runs1 <= 499) {
$tfif1 = $runs1 + $bonus3;
} else {
$tpor1 = $runs1;
}
/*condition for fifty 0 & 1 end */
/*condition for hundred 0 & 1 start */
if ($runs1 >= 100 && $runs1 <= 199) {
$hundred1 = 1;
}
else if ($runs1 >= 200 && $runs1 <= 299) {
$hundred1 = 2;
}
else {
$hundred1 = 0;
}
/*condition for hundred 0 & 1 end */
/*Condition start for Six excess to 3 sixes*/
$i1 = $sixes1 - 3;
if($i1 >= 1 && $i1 <= 500)
{
$tsix1 = $i1 * $bonus1;
}
else
{
$tsix1 == 0;
}
/*Condition start for Six excess to 3 sixes*/
if($fifty1 == 1 && $hundred1 >= 1)
{
$tsixhnrd1 += $bonus4;
}
/*condition for hundred 0 & 1 end */
if ($runs1 >= 100 && $runs1 <= 500) {
$trun1 += $bonus3;
}
$total_points1 = $tfif1+$tsix1+$tsixhnrd1+$trun1+$tpor1;
$total_score1 = $runs1;
/*veriable for Balling team database insertions end*/
?>
<form enctype="multipart/form-data" method="post" name="formA1">
<tr>
<td><div style="width:auto;padding-left:7px;font-size:17px;"><?php echo $player1;?></div>
<input type="hidden" name="player1" id="player1" value="<?php echo $player1;?>" />
<input type="hidden" name="matchid" id="matchid" value="<?php echo $matchid;?>" />
</td>
<?php
if($Status1=='P'){
?>
<td align="center">
<select id='status1' name='status1' onChange="dis_ableA1(this)">
<option value='NP'>NP</option>
<option value='P' selected>P</option>
<option value='O'>Out</option>
</select>
</td>
<td align="center">
<input type="text" onkeypress="return blockNonNumbers(this, event, false, false);" style="width:50px;height:25px;text-align:right;background:#f5c0c0;" name="runs1" id="runs1" value="<?php echo $runs1;?>" size="3" maxlength="3" />
</td>
<td align="center">
<input type="text" onkeypress="return blockNonNumbers(this, event, false, false);" style="width:30px;height:25px;text-align:right;background:#f5c0c0;" name="sixes1" id="sixes1" value="<?php echo $sixes1;?>" size="2" maxlength="2" />
</td>
<?php
} else if($Status1=='O'){
?>
<td align="center">
<select id='status1' style="width:50px;height:25px;" name='status1' onChange="dis_ableA1(this)">
<option value='NP'>NP</option>
<option value='P'>P</option>
<option value='O' selected>Out</option>
</select>
</td>
<td align="center">
<input type="text" onkeypress="return blockNonNumbers(this, event, false, false);" style="width:50px;height:25px;text-align:right;background:#ccc;" disabled name="runs1" id="runs1" value="<?php echo $runs1;?>" size="3" maxlength="3" />
</td>
<td align="center">
<input type="text" onkeypress="return blockNonNumbers(this, event, false, false);" style="width:30px;height:25px;text-align:right;background:#CCC;" disabled name="sixes1" id="sixes1" value="<?php echo $sixes1;?>" size="2" maxlength="2" />
</td>
<?php } else { ?>
<td align="center">
<select id='status1' style="width:50px;height:25px;" name='status1' onChange="dis_ableA1(this)" tabindex="1">
<option value='NP'>NP</option>
<option value='P'>P</option>
<option value='O'>Out</option>
</select>
</td>
<td align="center">
<input type="text" onkeypress="return blockNonNumbers(this, event, false, false);" style="width:50px;height:25px;text-align:right;" name="runs1" disabled id="runs1" value="<?php echo $runs1;?>" size="3" maxlength="3" />
</td>
<td align="center">
<input type="text" onkeypress="return blockNonNumbers(this, event, false, false);" style="width:30px;height:25px;text-align:right;" name="sixes1" disabled id="sixes1" value="<?php echo $sixes1;?>" size="2" maxlength="2" />
</td>
<?php }?>
<td align="center">
<label style="width:30px;height:25px;text-align:right;"><?php echo $fifty1;?></label>
<input style="width:30px;height:25px;text-align:right;" type="hidden" id="fifty1" name="fifty1" value="<?php echo $fifty1;?>" size='2' maxlength='2' />
</td>
<td align="center">
<label style="width:30px;height:25px;text-align:right;"><?php echo $hundred1;?></label>
<input style="width:30px;height:25px;text-align:right;" type="hidden" id="hundred1" name="hundred1" value="<?php echo $hundred1;?>" size='2' maxlength='2' />
</td>
<td align="center">
<label style="width:30px;height:25px;text-align:right;"><?php echo $total_points1;?></label>
<input style="width:30px;height:25px;text-align:right;" type="hidden" id="total_points1" name="total_points1" value="<?php echo $total_points1;?>" size='5' maxlength='5' />
<input type="hidden" name="allocation1" id="allocation1" value="pending" />
</td>
<?php
if($Status1=='P'){
?>
<td align="center">
<input type="submit" name="submitA1" id="submitA1" value="Save" />
</td>
<?php } else { ?>
<td align="center">
<input type="submit" disabled="disabled" name="submitA1" id="submitA1" value="Save" />
</td>
<?php } ?>
</tr>
</form>
<tr><td style="height:5px"></td></tr>
<!-- Insert Code Starts Submit1-->
<?php
if(isset($_POST['submitA1']))
{
$classObj->getPlayerPointTable();
$matchid = $_GET['mid'];
$cond = "player_name='".$player1."' AND match_no = '".$matchid."'";
$result = $classObj->selectSql($cond);
$count = $classObj->getAffectedRows($result);
//echo $count;
if($count > 0)
{
$player1up['status'] = $postedData['status1'];
//$player1up['player_name'] = $postedData['player1'];
$player1up['run_scored'] = $postedData['runs1'];
$player1up['sixs'] = $postedData['sixes1'];
$player1up['fifty'] = $postedData['fifty1'];
$player1up['hundred'] = $postedData['hundred1'];
$player1up['Total_Score'] = $postedData['total_score1'];
$player1up['point_scored'] = $postedData['total_points1'];
$player1up['allocation'] = $postedData['allocation1'];
$player1up['FirstPoint'] = $postedData['total_points1'];
$classObj->getPlayerPointTable();
$classObj->userPostedData = $player1up;
$cond = "match_no= '".$matchid."' AND player_name='".$player1."'";
$insert_query = $classObj->updateData($cond);
echo "<script> alert ('Player 1 update successfully.')</script>";
echo "<script>window.location='FirstIn.php?mid=$matchid'</script>";
}
else if($count <= 0)
{
$player['player_name'] = $postedData['player1'];
$player['match_no'] = $postedData['matchid'];
$player['status'] = $postedData['status1'];
$player['run_scored'] = $postedData['runs1'];
$player['sixs'] = $postedData['sixes1'];
$player['fifty'] = $postedData['fifty1'];
$player['hundred'] = $postedData['hundred1'];
$player['Total_Score'] = $postedData['total_score1'];
$player['point_scored'] = $postedData['total_points1'];
$player['FirstPoint'] = $postedData['total_points1'];
$classObj->userPostedData = $player;
$insert_query = $classObj->insertData();
if($insert_query == 'success')
{
echo "<script> alert('Player 1 score added.')</script>";
echo "<script>window.location='score.php?mid=$matchid'</script>";
}
}
else
{
echo "<script> alert ('Error Occured')</script>";
}
}
?>
Assuming that your class' getAffectedRows() method really fetches the affected rows from the last statement, it must be noted that a SELECT does not set this, it will be zero.
If you want to know how many lines were selected, use something like mysqli_num_rows.

arrange checkbox values in two columns

I have a form with check box values i want to arrange the checkbox in two columns instead of
one single long column.
How can i split it to two columns ?
Here is the code :
<form id="form" name="form" method="post" action="">
<table width="502" border="0">
<tr>
<td>
Name :
<input type="textbox" name="rcv_group_name" value="">
<input type="hidden" name="add" value="add" />
</td>
</tr>
<tr>
<td align="left">
<strong>HEADING</strong>
<?php
$q = "select * from Config_RCV";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) > 0)
{
$k=0;
while ($row = mysqli_fetch_array($r,MYSQLI_NUM))
{
?>
<br> <input type="checkbox" name ="rcv_val[]" value ="<? echo $row[0];?>" /> <? echo $row[1];?>
<?
$k++;
}
}
?>
</td>
</tr>
<tr>
<td align="right"><input type="submit" name="Submit" id="Submit" value="Submit" style="background-color:#999" />
< /td>
<td height="26" align="left"> </td>
<td> </td>
</tr>
</table>
<form>
add another table and make 2 columns by splitting 2'nd result:
if (mysqli_num_rows($r) > 0) {
$k=0;
echo '<table><tr>';
while ($row = mysqli_fetch_array($r,MYSQLI_NUM)) {
?>
<td><input type="checkbox" name ="rcv_val[]" value ="<?php echo $row[0];?>" /> <?php echo $row[1];?> </td>
<?php
$k++;
if($k%2 == 0){
echo '</tr><tr>';
}
}
echo '</table>';
}
use your $k
if ($k%2==0){
echo "<br />";
}
instead of the lone now
Using tables like above will probably be better for looks
You could just add a second column to your table:
echo "<tr>";
$i = 0;
while ($row = mysqli_fetch_array($r,MYSQLI_NUM)) {
if ($i++%2==0) {
echo "</tr><tr>";
}
echo "<td>".$CELL_CONTENT_HERE."</td>";
}
echo "</tr>";

if checkbox 1 checked select all checkboxes 2 where value in checkbox 2 IN checkbox 1 value array

I have several checkboxes, each representing individual team id. I have a few checkboxes above that each represent a group of those teams. I want to have the individual team checkboxes checked when that group is checked and visa versa. I am incredibly weak when it comes to javascript, and this might be basic but I cannot figure it out. My checkbox values are being pulled in php, and I am trying to avoid JQuery.
------------------PHP---Groups------------
<tr><th width="2%" class="thead1"></th><th class="thead1">Regions</th><th></th></tr>
<?php for ($i=0, $n=count( $this->regions111 ); $i < $n; $i++) {
$regions111 = $this->regions111[$i];?>
<tr><td><input type="checkbox" name="regionbox[]" value="<?php echo $regions111->id;?>"></td><td><?php echo $regions111->name;?></td></tr>
<?php }?>
--------------PHP-Individual Team ids---------------------------
<tr >
<th width="2%" class="thead1">
<input type="button" onclick="SetAllCheckBoxes('adminForm', 'teamarray2[]',true );" value="ALL" ><input type="button" onclick="SetAllCheckBoxes('adminForm', 'teamarray2[]',false );" value="None" > <th class="thead1">Teams
</th><th class="thead1">City</th>
</tr>
<?php
for ($i=0, $n=count( $this->rows ); $i < $n; $i++) {
$row = $this->rows[$i];
?>
<tr class="etblraw<?php echo $i % 2?>"><td>
<input type="checkbox" name="teamarray2[]" value="<?php echo $row->id;?>" <?php if (in_array("$row->id",$this->henry5)){echo 'checked="checked"';}else{}?> >
</td>
<td>
<?php
echo $row->t_name;
?>
</td>
<td>
<?php echo $row->t_city;?>
</td>
</tr>
--------------------End-PHP-----------------------------
----------------Javascript-select all function------------------
function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
if(!document.forms[FormName])
return;
var objCheckBoxes = document.forms[FormName].elements[FieldName];
if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = CheckValue;
}
-----------------end Js------------------------------------------

Categories