zhwatts zhwatts - 6 months ago 7
PHP Question

Is it possible to reference similar SQL column names from joined tables using PHP

I have a few tables joined together, but several of the columns have similar names. I'm using php to fetch those values, but I am unable to use the sql identifier in php to pick the correct column... i.e. in SQL I have two tables Register and Jurisdict. both of them have a column called "name". in SQL I can reference these columns as such

r.name
j.name


and these would give me values from the two different tables. However in I PHP am not able to use the r. or j. and anytime I use name it returns which ever table is selected first in the SQL statement.

Here is my current code

<?php


$sql = "
SELECT j.rpt_name, r.name
FROM [SMARTCM] . [dbo] . [REGISTER] r

join [SMARTCM] . [dbo] . [jurisdict] j
on j.UniqueKey = r.FK_JURSDICT_KEY

$stmt = sqlsrv_query( $conn, $sql );

?>


I'm using a while loop to generate the PHP, with this tag to reference the column

<?php echo $row['name']; ?>


However it breaks if I try and use the table reference (r.name) like i would i sql

Answer

you need to use aliasing feature of SQL query..

<?php


    $sql = "
SELECT j.name as j_name, r.name as r_name 
FROM [SMARTCM] . [dbo] . [REGISTER] r

join [SMARTCM] . [dbo] . [jurisdict] j
on j.UniqueKey = r.FK_JURSDICT_KEY";

$stmt = sqlsrv_query( $conn, $sql );


echo $row['j_name'];

echo $row['r_name'];
?>