Hi,
I'm trying to update a field called "order_by" with an integer provided from a form which lists sources by subject, queried from the database.
The problem I'm having (as I was able to determine by echoing rows) is that instead of looping through each of the source_ids and assigning it an associated order_by, it just picks the very last source_id on my list, and then applying each order_by to that in sequence, resulting in only one eventual update to one source_id.
When echoing the rows below, I get in order: subject_id, source_id, order_by as the following (subject id is correct; these are all drawn from the GET from the URL)
3, 106, 5
3, 106, 3
3, 106, 2
3, 106, 1
3, 106, 9
3, 106, 7
the actual source_ids are all different, and I was able to tell because I have echoed them before each row in the form. Any ideas how to get around this?
Here's my (simplified) code:
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die('Error connecting to MySQL server.');
//grab subject id
$subject_id = $_GET['subject_id'];
//grabs the subject name to associate with the id
$q1 = "SELECT subject_id, subject_name from subject where subject_id = $subject_id ";
$r1 = mysqli_query($dbc, $q1)
or die ('Error querying database');
?>
<?php
//grabs the source name, and other relevant information for display, and subject name to associate with id.
$qs = "SELECT s.source_id, s.source_name, s.description, s.url, s.proxy_ind, sb.subject_id, sb.subject_name, ss.order_by
from source s, source_subject ss, subject sb
where s.source_id = ss.source_id
and sb.subject_id = ss.subject_id
and sb.subject_id = $subject_id
order by source_name";
$rs = mysqli_query($dbc, $qs)
or die ('Error querying database');
//$subject_name = $row['subject_name'];
//echo the subject name, create link associated with id
//update row order
if (isset($_POST['submit'])) {
//get variables, and assign order
$source_id = $_POST['source_id'];
//echo 'Order by entered as ' . $order_by . '<br />';
foreach ($_POST['order_by'] as $order_by) {
//$order_by = $_POST['order_by'];
$qorder = "UPDATE source_subject set order_by = '$order_by'
WHERE source_id = '$source_id'
AND subject_id = '$subject_id'";
mysqli_query($dbc, $qorder)
or die ('could not insert order');
echo $subject_id . ', ' . $source_id . ', ' . $order_by;
echo '<br />';
}
}
while($row = mysqli_fetch_array($rs)) {
$subject_id = $_GET['subject_id'];
$order_by = $row['order_by'];
$source_id = $row['source_id'];
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'].'?subject_id='.$subject_id ; ?>">
<?php
echo $source_id . '<input type="hidden" name="source_id" value="'. $row['source_id']. '" ><input type="text" id="order_by" name="order_by[]" size="1" value="'. $order_by .'"/> <a href="'. $row['url'] .'" target="_blank">'. $row['source_name'] . '</a> <br />';
}
?>
<input type="submit" value="update" name="submit" /><p />
</form>