Multiple left joins, how to output in php

Posted by Dan on Stack Overflow See other posts from Stack Overflow or by Dan
Published on 2010-04-14T06:45:10Z Indexed on 2010/04/14 6:53 UTC
Read the original article Hit count: 219

Filed under:
|
|
|
|

I have 3 tables I need to join. The contracts table is the main table, the 'jobs' and 'companies' table are extra info that can be associated to the contracts table.

so, since I want all entries from my 'contracts' table, and the 'jobs' and 'companies' data only if it exists, I wrote the query like this....

$sql = "SELECT * FROM contracts
        LEFT JOIN jobs ON contracts.job_id = jobs.id
        LEFT JOIN companies ON contracts.company_id = companies.id
        ORDER BY contracts.end_date";

Now how would I output this in PHP? I tried this but kept getting an undefined error "Notice: Undefined index: contracts.id"...

$sql_result = mysql_query($sql,$connection) or die ("Fail.");

if(mysql_num_rows($sql_result) > 0){

    while($row = mysql_fetch_array($sql_result))
    {
       $contract_id = stripslashes($row['contracts.id']);
       $job_number = stripslashes($row['jobs.job_number']);
       $company_name = stripslashes($row['companies.name']);
    ?>
        <tr id="<?=$contract_id?>">
           <td><?=$job_number?></td>
           <td><?=$company_name?></td>
        </tr>
    <?  
    }
}else{
    echo "No records found";
}

Any help is appreciated.

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql