I have refereed and tried many solutions provided in this type of question threads before asking my question as none of them working properly for me. I have one mysql table of students which stores stud name, marks. I am retrieving that data from database using while loop.
$query="select * from student";
$rs= mysql_query($query) or die(mysql_error());
<?php if(mysql_num_rows($rs)){ ?>
<table border="5" cellspacing="5" width="50%" align="center">
<tr>
<th>No</th>
<th>Name</th>
<th>Marks</th>
<th>Operation</th>
<th> <input type ="submit" name="delete" value="Delete"></th>
</tr>
<?php
while($row=mysql_fetch_array($rs))
{
?>
<tr>
<th><?php echo $row['rollno']; ?></th>
<th><?php echo $row['name']; ?></th>
<th><?php echo $row['marks']; ?></th>
<th><a href="AllOperation.php?&no=<?php echo $row['rollno']; ?>&name=<?php echo $row['name']; ?>&marks=<?php echo $row['marks']; ?>">View</a></th>
<th><input type="checkbox" name="check[]" value="<?php echo $row['marks']; ?>" <?php if(isset($_POST['check'])) if (in_array($row['marks'], $_POST['check'])) echo "checked='checked'"; ?> /></th>
</tr>
<tr>
<?php } ?>
<input type ="submit" name="total" value="total">
And i am generating the total of marks of all the students
if(isset($_POST['total']))
{ $t=0;
foreach($_REQUEST['check'] as $val)
{
$t=$t+$val;
}
echo " total : ".$t;
}
Now problem is that when first time i run the program it displays 5 student's information and than i selected first two checkbox and press the "total" button to generate the total. So it displays the total properly and keep that two check boxes checked. But when i checked third checkbox and press the "total" button than it shows the total of that three selected check box's marks but it display 4th or last checkbox checked even if i did't checked it. So why that is happening.
mysql_*-functions. They have been deprecated since PHP 5.5 (in 2013) and were completely removed in PHP 7 (in 2015). Use MySQLi or PDO instead.check[](which means that they will be posted as an array), and even if you have checked the third and the last, you will get an array containing only two elements (with index 0 and 1). It doesn't tell you in which position those checkboxes were in the form.isset($_POST['check'])on every row, which only tells you if any checkbox is checked, not if that specific checkbox was checked.rollnorather thanmarks. In case you needmarksvalue, you can try:<th><input type="checkbox" name="check[<?php echo $row['rollno']; ?>]" value="<?php echo $row['marks']; ?>" <?php if(isset($_POST['check']) and isset($_POST['check'][$row['rollno']])) echo "checked='checked'"; ?> />marksis not an identity column, should not use it to identify checkbox.