First of all I confess I am very new to PHP programming. Here is my problem. I just wanted to create a registration page for students. In that I need to populate the classes which the students want to enroll in checkboxes from database(because a student can enroll n number of classes and I am planning to give admin options for creating and deleting classes so I need to populate from database). Obviously that has been done. I populated the values from database as checkboxes. For that I used the following code

<?php
$dbhandle = mysql_connect("localhost","root","")or die(mysql_error());
mysql_select_db("my_db",$dbhandle)or die("Could not lkb");
$data =  mysql_query("select * from classes") or die(mysql_error());
while ($val = mysql_fetch_array($data))
{  ?> <input type="checkbox" name="classes" id="classes" value="<?php print $val['id']; ?>"> <?php print isset($val['class_name'])?$val['class_name']:"";  ?> <br> <?php }
?>

This part has been done.
Yet my exact problem is now I want to save the student data in one table and the classes(one which populated from database as checkboxes) in a separate detail table. I mean Student_id, class_id. In this table i want to save student_id repeatedly up to the number of selected classes(checkboxes) he or she chooses for final report generating purpose.
(For ex: stud_001 1,stud_002 5,stud_002 2,stud_002 3,stud_003, 6)For achieving this I tried the following code but it doesn't working.

<?php
    $checkbox1 = $_POST['classes'];
    if ($_POST["submit"] == "submit"){
    for( $i=0 ; $i<sizeof($checkbox1); $i++){
    $query = "insert into stud_class (class_id) values ('"$checkbox1[$i]"')";
    mysql_query($query) or die (mysql_error());
    }
    echo "Record Inserted";
    }

Please help me. Thanks in advance!!!

Recommended Answers

All 2 Replies

First of all, mysql_* is already depreciated. It is encourraged to use the PDO or mysqli_* instead.

For you problem, here is what doesn't work in php:
for( $i=0 ; $i<sizeof($checkbox1); $i++)
In php, we use
for( $i=0 ; $i<count($checkbox1); $i++)

and the query
$query = "insert into stud_class (class_id) values ('"$checkbox1[$i]"')";
should having the joining
$query = "insert into stud_class (class_id) values ('".$checkbox1[$i]."')";

Hi lps Thank you so much for your kind and concerned reply over on my question with in half an hour.This is my first post after I joined in daniweb a few minutes ago. I didn't expect this quick and quality answer. I'm excited and your coding working awesome. Thank you once again I really wanted to keep in touch with you. May I?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.