由不同的组sql分开学生

时间:2016-12-27 08:40:26

标签: php mysql sql for-loop nested-loops

如何分隔学生并使用两个嵌套的for循环来存储数据..?

$jobID              =   85
$gd_individuals     =   4 ;

$studentQuery = $conn->query(" select s.student_pid,i.email,s.student_email, s.student_fname,
       s.student_lname,s.profile_pic from r_job_invitations i 
       LEFT JOIN tbl_students s ON i.email = s.student_email 
      where i.id_job = ".$jobID." and inv_res = 1");

//$studentResults = $studentQuery->fetch_assoc();   //total 8 students
$totalIndividuals    = mysqli_num_rows($studentQuery); //total 8 students

$groups = 2   //which is coming from total/gd_individual 8/4=2

for($j = 0; $j<$groups; $j++)   {

while($studentResults = $studentQuery->fetch_array()){    //total 8 studnets

echo "INSERT INTO r_test_group 
        (student_id,job_id,group_name) 
        values (".$studentResults['student_pid'].", ".$jobID.",Group".$j." )";


           }
        }
        exit;
    }

我想将前4名学生作为group1存储,将第4名学生作为group2 等存储。

myresult就是这样来的

INSERT INTO r_test_group (student_id,job_id,group_name) values (22, 85,Group0 )
INSERT INTO r_test_group(student_id,job_id,group_name) values (23, 85,Group0 )
INSERT INTO r_test_group (student_id,job_id,group_name) values (25, 85,Group0 )
INSERT INTO r_test_group (student_id,job_id,group_name) values (26, 85,Group0)
INSERT INTO r_test_group (student_id,job_id,group_name) values (27, 85,Group0 )
INSERT INTO r_test_group(student_id,job_id,group_name) values (28, 85,Group0 )
INSERT INTO r_test_group (student_id,job_id,group_name) values (29, 85,Group0 )
  

我要找的实际结果是前4名学生是group1和   第二组4组等......

1 个答案:

答案 0 :(得分:1)

试试这个:

      $studentResults = $studentQuery->fetch_array();
    $counter  = 0;
    for($j = 0; $j<$groups; $j++)   {
    for($i = 0; $i<4; $i++){
    echo "INSERT INTO r_test_group 
            (student_id,job_id,group_name) 
            values (".$studentResults[$counter]['student_pid'].", ".$jobID.",Group".$j." )";
   $counter++;
    }
    }