简体   繁体   中英

using variable in mysql_fetch_assoc to output data from a column in a multi row.?

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.

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.

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"];

(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM