Mena Mena - 2 years ago 123
MySQL Question

Form field value not sent on update

I have a form that allows a user to input scores for multiple students and specify which test (either test1, test2, or test3) the scores would be recorded for. An echo of my query reveals that only the first row of data is being sent to the sql update statement while others seem to get truncated (cut off completely.)

Here's my code:

if (isset($_POST['submit'])) {

# process the form
$student_id = $_POST["student_id"];
$subject_id = $result['subject_id'];
$type = $_POST["type"];
$score = $_POST["score"];

for($i=0; $i < count($student_id); $i++) {
$studentid = mysqli_real_escape_string($connection, $student_id[$i]);
$subjectid = mysqli_real_escape_string($connection, $subject_id);
$type = mysqli_real_escape_string($connection, $type);
$score = mysqli_real_escape_string($connection, $score[$i]);

$query = "UPDATE records SET $type='{$score}' WHERE student_id={$studentid} AND subject_id={$subjectid}";
//$result = mysqli_query($connection, $query);
echo $query;

As an example, if the values 10, 11 and 12 are entered into the form I get the following output from an echo of my $query

UPDATE records SET test1=' 10' WHERE student_id=53 AND subject_id=2
UPDATE records SET test1='1' WHERE student_id=54 AND subject_id=2
UPDATE records SET test1='' WHERE student_id=55 AND subject_id=2

and the following error

Notice: Uninitialized string offset: 2 on line ---- $score = mysqli_real_escape_string($connection, $score[$i]);

Why is this happening and how can I fix this?

Answer Source

You overwrite array $score. It shoud look like this:

$scoreOther = mysqli_real_escape_string($connection, $score[$i]);

and put $scoreOther into query not $score then

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download