Skip to content Skip to sidebar Skip to footer

Replacing A Pulled Sql Id Value With Its Name From Another Table

I have some code (see below) that populates a table with all the records. I however want to replace the ID that is presented for site_id with its actual name which is stored in ano

Solution 1:

I would advise a very simple SQL join. Assuming the site name is sitename in the sites_tbl:

$sql  = "SELECT sheet.sheet_id, sheet.username, site.sitename FROM sheet_tbl S
       JOIN sites_tbl ST ON ST.site_id = S.site_id ";
$stmt = $conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();


  <?php foreach ($data as $row): ?>
    <tr>
        <td><?=$row['sheet_id']?></td>
        <td><?=$row['username']?></td>
        <td><?=$row['sitename']?></td>
   </tr>

So now you not only have the data from sheet_tbl but also the associated data from sites_tbl that you can now use directly.

Read more about joins here: http://www.w3schools.com/sql/sql_join.asp


Solution 2:

You can join the tables together;

select  sheet.sheet_id
,       sheet.username
,       site.sitename
from    sheet_tbl sheet
join    sites_tbl site
on      sheet.site_id = site.site_id

Post a Comment for "Replacing A Pulled Sql Id Value With Its Name From Another Table"