tags:

views:

69

answers:

3

if i have a query like this

$query = mysql_query("
SELECT * FROM tbl_school
INNER JOIN tbl_livingexp ON (tbl_school.schoolname=tbl_livingexp.schoolname)
INNER JOIN tbl_tuition ON (tbl_school.schoolname=tbl_tuition.schoolname)
INNER JOIN tbl_apprequirments ON 
(tbl_school.schoolname=tbl_apprequirments.schoolname) 
where tbl_school.schoolname = '$schoolname'");

and 3 of the tables contain a column named language.
when i begin to write this code.

while($row = mysql_fetch_assoc($query)) {
//output.

how do i output the column language from only the table tbl_school if i were to type it like this?

$row['language'];  ?

i tried $row['tbl_school.language']; but that gave me an error.

+1  A: 

You have to explicitly name them:

SELECT a.foo first_col, b.foo second_col, c.foo third_col
FROM a, b, c
WHERE [conditions]

If you fetch the data using

$row = mysql_fetch_assoc($query);

you can now access the columns using $row["first_col"], $row["second_col"] and $row["third_col"]. This is due to how the mysql client library works. The table name simply won't be prepended to the column name. This means that every column name has to be unique in order to appear in the result.

Emil H
ohhh. now i see what those are used for. i took a mysql course at college and the teacher did just that. and i couldnt find a purpose for it aside from a lazy coder.
thank you for your input.
+1  A: 

In production code, try to avoid SELECT * at all costs. You need to explicitly list your column names in the query:

SELECT 
  le.schoolname, 
  le.language AS livingexp_language, 
  t.language AS tuition_language,
  ...
FROM tbl_school
INNER JOIN tbl_livingexp AS le ON (tbl_school.schoolname=tbl_livingexp.schoolname)
INNER JOIN tbl_tuition AS t ON (tbl_school.schoolname=tbl_tuition.schoolname)
...

Use:

$row["livingexp_language"];
John Rasch
its too much work to write all that :( but i guess ur right.
@sarmenhb - Indeed, it's fine if it's just something you're messing around with, but if this is code that other people are going to have to maintain, imagine if a new column were added to the database or an existing one were modified (as in a column's name was changed to reflect some new naming scheme)... that would be much much more work to deal with the now broken application than it would have been to explicitly list the columns in the first place :)
John Rasch
thank you all for inputs
+1  A: 

(For the sake of completeness) You can also achieve the same thing by using mysql_fetch_row rather than mysql_fetch_assoc, which puts your results in a numeric array that you can reference thusly:

$row = mysql_fetch_row($query);
$id = $row[0];
$language = $row[1]; // for instance

In this case, it's even more important to avoid SELECT * as it makes it very easy to make mistakes and hard to debug.

da5id