Jump to content

While loop and Array Problem


padawan

Recommended Posts

These are my tables and fields.

 

student_info(table) contains ( id(PK), student_name)

student_subject(table) contains ( id(PK), student_id(FK), subject_name)

 

below is my query:

 


$getRecords= mysql_query("select student_info.id, student_name, student_subject FROM student_info,student_subject WHERE student_info.id = student_subject.student_id");

	while($getresult=mysql_fetch_assoc($getRecords))
	{
	$arr[] = array('id' => $getresult['id'], 'subjects' => $getresult['subject_name'],  'name' => $getresult['student_name']), 
	}

 

In student_subject table I have at least 5 subjects(different rows) pointing to the same student. But the variable subjects in the array can  only get 1 value how I can get those other subjects  :confused:.  I need simple solution/query coz I just started learning about this.  Thank you for your help

Link to comment
Share on other sites

These are my tables and fields.

 

student_info(table) contains ( id(PK), student_name)

student_subject(table) contains ( id(PK), student_id(FK), subject_name)

 

below is my query:

 


$getRecords= mysql_query("select student_info.id, student_name, student_subject FROM student_info,student_subject WHERE student_info.id = student_subject.student_id");

	while($getresult=mysql_fetch_assoc($getRecords))
	{
	$arr[] = array('id' => $getresult['id'], 'subjects' => $getresult['subject_name'],  'name' => $getresult['student_name']), 
	}

 

In student_subject table I have at least 5 subjects(different rows) pointing to the same student. But the variable subjects in the array can  only get 1 value how I can get those other subjects  :confused:.  I need simple solution/query coz I just started learning about this.  Thank you for your help

 

Hi, the sql looks correct to me, i have tried and it worded for me...

 

and looking to your PHP the problem seems that for instance :

 

you return from your DB:

ID 4 Name XXX Subject YYY

ID 4 Name XXX1 Subject ZZZ

 

you put that in one array that will overlap the index 4...

 

try to print the instead of saving in one array to validate my theory.

Link to comment
Share on other sites

I would do something like this:

 

$arr = array();
$getRecords= mysql_query("select student_info.id, student_name, student_subject FROM student_info,student_subject WHERE student_info.id = student_subject.student_id");

while($getresult=mysql_fetch_assoc($getRecords)){
$arr[$getresult['id']]["name"]= $getresult['student_name'];
$arr[$getresult['id']]["subjects"][] = $getresult['subject_name'];
}
print_r($arr);

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.