Anton
Anton

Reputation: 429

Combining sql queries in PHP

Hello currently working with this code

   $qry_display = "
SELECT 
    student_id,
    fname,
    sex,
    lname,
    mname,
    level,
    photo,
    birth_date,
    birth_place,
    address,
    father,
    father_occupation,
    father_phone,
    father_company,
    father_degree,
    mother,
    mother_occupation,
    mother_phone,
    mother_company,
    mother_degree,
    adviser_id 
from 
    tbl_enroll 
where 
    student_id='$id' 
    AND level='$lvl'

";
    $sql_display = mysql_query($qry_display) or die (mysql_error());

The above code fetches most data from tbl_enroll. Now I want to acquire some data on tbl_er. tbl_enroll and tbl_er are connected with the primary key of student_id , also connect once to tbl_section. tbl_er and tbl_section are connected with the foreign key of section_id.

So far I was thinking of doing multiple sql queries and use one mysql_query trigger but it wont work because the trigger wont work with three sql queries.

Upvotes: 5

Views: 531

Answers (5)

LaGrandMere
LaGrandMere

Reputation: 10359

   SELECT te.XXX,tr.YYYY,ts.ZZZ, ..... 
   from tbl_enroll te 
   inner join tbl_er tr on tr.student_id = te.student_id
   inner join tbl_section ts on ts.section_id = te.section_id
   where student_id='$id' and level='$lvl';

You select any field from te, tr or ts at the beginning of your query. Don't forget to prefix with te, tr or ts the fields so that you don't have ambiguous references when executing the query ;)

Upvotes: 2

Suresh kumar
Suresh kumar

Reputation: 2092

you can try by following systax

select tb1.filds,tb2.fields ... from table1 as tb1, table2 as tb2 .. where tb1.id = tb2.id and tb2.id  = tb3.id ...

In where condition have to check correctly.

else you can use Join Query .. .Join Query is better on

Upvotes: 2

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79929

Just JOIN the three tables:

SELECT t1.*, t2.*, t3.*
from tbl_enroll t1
JOIN tbl_el t2 ON t1.student_id = t2.student_id
JOIN tbl_section t3 ON t2.section_id = t3.section_id
where student_id='$id' AND a.level='$lvl'

Upvotes: 8

Basith
Basith

Reputation: 1075

Combining two queries..

SELECT t1.* FROM tbl_er as t1, tbl_enroll as t2
WHERE t1.student_id= t2.student_id ORDER BY id DESC

You have to define the student id in both tables..

Upvotes: 1

Jens
Jens

Reputation: 2075

You should join the tables. This isn't about php but about sql.

Upvotes: 6

Related Questions