0

last time I ask how to save a loop to a database now want to show the values inside the table and then update it but it only saves the last row.

$id = ($_REQUEST['StudentNumber']);
$result2= mysql_query("select NameofSiblings, Age, HEA, CivilStatus, Occupation FROM $tblname WHERE StudentNumber='$id'");

$child = $_REQUEST['NumberofChildren'];
for($n=1;$n<=$child;$n++)
{
    while($row=mysql_fetch_array($result2))
    {

        echo "<table>
        <tr>

        <td class='siblings'><input type='text' name='sibname[]' style='width: 150px;' value=".$row['NameofSiblings']."></td>
        <td class='siblings'><input type='text' name='sibage[]' style='width: 35px;' value=".$row['Age']."></td>
        <td class='siblings'><input type='text' name='sibhea[]' style='width: 260px;' value=".$row['HEA']."></td>
        <td class='siblings'><input type='text' name='sibcs[]' style='width: 100px;' value=".$row['CivilStatus']."></td>
        <td class='siblings'><input type='text' name='siboccu[]' style='width: 100px;' value=".$row['Occupation']."></td>
        </tr>       
        </table>";
    }
}
?>
<input type="hidden" name="n" value="<?php echo $child; ?>">

Am I doing it right? And this is my update query:

$n=intval($_POST['n']);
for($i=0;$i<$n;$i++)
{
    $sibname =$_POST['sibname'][$i];
    $sibage =$_POST['sibage'][$i];
    $sibhea =$_POST['sibhea'][$i];
    $sibcs =$_POST['sibcs'][$i];
    $siboccu =$_POST['siboccu'][$i];

    $query = "UPDATE $tblname SET NameofSiblings = '$sibname', Age = '$sibage', HEA = '$sibhea', CivilStatus = '$sibcs', Occupation = '$siboccu' WHERE StudentNumber='$sn' ";
}

I hope someone can understand it.

1 Answers1

0

When you loop through the POST values, you create a SQL query string yet you don't execute it (ie call mysql_query) within the loop (or outside it for that matter). You need to execute the query before the next iteration of the loop occurs or you will lose the value.

for ($i=0; $i<$n; $i++) {
    $sibname =$_POST['sibname'][$i];
    $sibage =$_POST['sibage'][$i];
    $sibhea =$_POST['sibhea'][$i];
    $sibcs =$_POST['sibcs'][$i];
    $siboccu =$_POST['siboccu'][$i];

    $query = "UPDATE $tblname SET NameofSiblings = '$sibname', Age = '$sibage', HEA = '$sibhea', CivilStatus = '$sibcs', Occupation = '$siboccu' WHERE StudentNumber='$sn' ";

    mysql_query($query); // execute query here for each iteration of the loop
}

Hope that makes sense, you should stop using the mysql_* functions as they are deprecated now and are very vulnerable to SQL injection attacks.

Take a look at these links, which should help a lot.

  1. How can I prevent SQL injection in PHP?
  2. PHP The Right Way
Community
  • 1
  • 1
SamV
  • 7,548
  • 4
  • 39
  • 50