Inserting Multiple Rows in MySQL using For Loop

Hi Everyone,
(Please i need help with my school project)
I’ve been trying to insert Multiple Rows into a MySQL Table using for loop.
(it’s basically inserting the attendance of n number of students)
Everything seems to work fine but when i check the Table, I see that only the Last Row in the array is inserted. what could i be doing wrong, or please suggest a better way to do this.

below is my code snippet
[php]

for ($i = 1; $i < count($rollno); $i++) {
$query = “INSERT INTO lectures(
course_code, lecturer_id, student_id, lecture_desc, attended, lecture_type, date, time)
VALUES(’$course_code[$i]’, ‘$regno[$i]’, ‘$lecturer_id’, ‘$lecturetype’, ‘$present[$i]’, ‘$topic[$i]’, ‘$date’, ‘$time’)”;
}
if (mysql_query($query, $mysqlconnection)){
//success
}
else{
echo “

Operation failed. Try again Later

”;
echo “

” . mysql_error() . “

”;
exit(1);}
[/php]
I receive No error message but only the last row iin the loop is inserted.
Please Help.
Thanks alot.

Php issue.

Why are you starting the loop at 1 instead of 0?

its only doing the last row because you execute the query outside the loop. Below is how i did something like what you’re trying to
[php]
if(isset($_POST[‘permclose’])) {
for($i = 0; $i < count($_POST[‘ck’]); $i++) {
$rid = $_POST[‘ck’][$i];
mysql_query(“UPDATE contactus SET status = 0, permclose = 1 WHERE req_id = ‘$rid’”) or die(mysql_error());
}
}[/php]
$_POST[‘ck’] comes from

Your query looks fine, just need to move the mysql_query part inside the loop. Either that, or make $query into an array and put the mysql_query in a seperate for loop.

Sponsor our Newsletter | Privacy Policy | Terms of Service