2012-04-04 2 views
0

여기에 내가 4 개 개의 테이블는 MySQL의 표는

다음
SELECT DISTINCT c.title as CourseTitle, t.title as TopicTitle, l.title as LessonTitle, r.title as ResourceTitle, r.location, r.type, r.duration 
FROM j17_lessons l, j17_topics t, j17_courses c, j17_resources r 
WHERE 
CONCAT(c.title, t.title, l.title, r.title, r.type, r.location) LIKE '%Fatih%' 
AND c.id = t.course_id 
AND l.topic_id = t.id 
AND r.lesson_id = l.id 
ORDER BY c.title, t.id, l.id, r.id; 

에서 MySQL의 결과를 가져 오기 위해 사용하고 내 코드입니다의 스크린 샷을 내 가져 오기 이제 http://i40.tinypic.com/2v1w0ib.png

결과 열 이름으로 결과를 필터링 가입 무엇 나는 각각의 'CourseTitle'에 대한 HTML 테이블을 데이터베이스에 생성 할 필요가있다.

내가 첫 번째 쿼리에 대한 결과를 얻을 수있는 SQL 문 및 PHP 코드를 사용하지만 난 분할 두 번째 질의를 필요로한다 테이블 foreach는 'CourseTitle'

/* connect to the db */ 
$connection = mysql_connect('localhost','root','123'); 
mysql_select_db('alhudapk',$connection); 

/* show tables */ 
$result = mysql_query('SELECT DISTINCT c.title as CourseTitle, t.title as TopicTitle,  l.title as LessonTitle, r.title as ResourceTitle, r.location, r.type, r.duration 
FROM j17_lessons l, j17_topics t, j17_courses c, j17_resources r 
WHERE 
CONCAT(c.title, t.title, l.title, r.title, r.type, r.location) LIKE '%Taleem%' 
AND c.id = t.course_id 
AND l.topic_id = t.id 
AND r.lesson_id = l.id 
ORDER BY c.title, t.id, l.id, r.id',$connection) or die('cannot show tables'); 
while($tableName = mysql_fetch_row($result)) { 

$table = $tableName[0]; 

echo '<h3>',$table,'</h3>'; 
$result2 = mysql_query('SELECT '.$table . 'AS' .$table); 
if(mysql_num_rows($result2)) { 

정확하고 더 나은 코드

+1

디자인에 테이블/필드 이름을 다른 필드에 저장해야하는 경우 디자인을 다시 작성해야합니다. 그것은 매우 빨리 엉망이 될 것입니다. –

답변

1

내가 할 수있는 것은 데이터를 출력해야하는 순서대로 배열 된 큰 배열 구조에 넣는 것입니다. 이렇게하면 코드를 좀 더 쉽게 유지할 수 있습니다.

// run the query as you did in the question 

$courses = array(); 

// use mysql_fetch_assoc as it makes the code clearer 
while($row = mysql_fetch_assoc($result)) { 
    $ct = $row['CourseTitle']; 
    // Found a new Course Title? If so create an array to put the data rows in 
    if(!isset($courses[$ct])) 
     $courses[$ct] = array(); 

    // add this row to the end of its course array 
    $courses[$ct][] = $row; 
} 

// now print the results out 
foreach($courses as $title =>$course) { 
    echo "<h3>$title</h3>"; 
    echo "<table>"; 
    foreach($course as $line) { 
     echo "<tr><td>" . $line['TopicTitle'] . "</td><td>" 
      . $line['LessonTitle'] . "</td></tr>"; 
    echo "</table>"; 
} 

위의 코드는 처음 2 열 을 인쇄하지만, 당신이 얻을 수 있다면 그것은 당신이 아주 쉽게 나머지를 추가 할 수 있어야 작동 할 수 있습니다.

+0

페이지 결과가 비어있다. ( – Amanullah

+0

) 디버그 라인을 추가 해보자. while 루프의 끝에 다음을 넣을 수있다 : echo "라인 추가하기 . " – Annabel

+0

while 루프가 print_r ($ courses);를 입력 한 다음보기 원본을 사용하여 나오는 내용을 확인하십시오. 어쩌면 문제가 쿼리가 작동하지 않는 것일 수도 있습니다 .. – Annabel

0
를 구축 나를 인도 해주십시오

추가 :

GROUP BY c.title 

SQL 문의 끝.

+0

나는 SQL 쿼리를 관리 할 것이다. foreach 컬럼 이름으로 – Amanullah