-2

This is the input fields

<?php while($educationalQualificationsFromDB = Database::fetchData($queryForEducationalQualifications))
                {
                    $eduQualifcationId = $educationalQualificationsFromDB['education_qualification_id']; 
                    $eduQualifcation = $educationalQualificationsFromDB['edu_qualification']; 
    
                    echo "<input class='form-control' type='text' name='eduqualification[]' value='$eduQualifcation'>";
                    echo "<br>";
                } 
                
                ?>

This is the query I used,

$eduQualifications = $_POST['eduqualification'];

foreach($eduQualifications as $oneEduQualifications)
       {
            Database::query("UPDATE educational_qualification SET edu_qualification = '$oneEduQualifications'");
       }

I'll simply explain like this there are multiple values coming from the database from the educational qualifications table.I have used a while loop to fetch them all inside inputs.And there are several inputs right.So I need a condition to update all those relevant database data.I used foreach loop to fetch data from the inputs cause i used the name of the input fields as an array.When I update them using foreach loop it update all records with the same name.Please explain me why such thing happened and give me a solution to update all relevant multiple database values with the relevant input values.

Mishen Thakshana
  • 143
  • 1
  • 12

1 Answers1

0

An UPDATE query will update all rows, unless constrained to specific rows by a WHERE clause. So you'll need to add something like:

UPDATE educational_qualification
   SET edu_qualification = '$oneEduQualifications'
 WHERE education_qualification_id = '$eduQualifcationId'

So you need to transport the $eduQualifcationId through the form together with the $eduQualifcation as well. The best way for that is to just use it as the $_POST array key:

<input type='text' name='eduqualification[$eduQualifcationId]' value='$eduQualifcation'>

Now your $_POST array will look something like:

array(
  'eduqualification' => array(
    '42' => '69'
  )
)

So you can do:

foreach ($_POST['eduqualification'] as $id => $qualification) {
    Database::query("UPDATE educational_qualification SET edu_qualification = '$qualification' WHERE education_qualification_id = '$id'");
}

As is, you appear to be open to both SQL and HTML injection BTW, which you'll want to fix:

If you have multiple users, and certain users should only be allowed to update their own data, then you'll want even more constrains and checks, something like:

UPDATE educational_qualification
   SET edu_qualification = '$oneEduQualifications'
 WHERE education_qualification_id = '$eduQualifcationId'
   AND user = '$current_user'

Because POST requests are just HTTP requests, and anyone can send any arbitrary data in an HTTP request…

deceze
  • 510,633
  • 85
  • 743
  • 889