I have a table whose primary key is a column named St_ID
. I want to update another column in that same (ID
) using values stored in an array. But when I try the code below, the result is a new record with an St_ID
value of '0' and all other columns are empty.
Note, courseID
is a value chosen through a drop down list. Do you have any idea where I went wrong?
for ($i = 0; $i < $count; $i++){
$Student = $foo[$i];
$res = mysql_query("SELECT St_ID FROM student WHERE St_ID='$Student' ");
while($row = mysql_fetch_array($res))
{
$sql = "INSERT INTO student (ID) VALUES
('" . $_POST[$row['courseID']] . "')";
}
}
if (!mysql_query($sql,$connectdb))
{
die ('Error :'.mysql_error());
}
echo "The Students are add to the course <br />";
Here simplified code, with only one query
$where = "'".implode("','", $foo)."'";
$res = mysql_query("UPDATE student set ID = courseID WHERE St_ID IN ($where)")
or die('Error :'.mysql_error());
echo "The Students are add to the course <br />";
you select St_ID
but try to insert courseID
in this line
$sql = "INSERT INTO student (ID) VALUES
('" . $_POST[$row['courseID']] . "')";
SELECT St_ID FROM student WHERE St_ID='$Student'
INSERT INTO student (ID) VALUES ...
If you want to update that record you chose, you must use the UPDATE sql command instead;
UPDATE student
SET ID=...
WHERE St_ID='$Student'