php - Replacing a pulled SQL ID value with its name from another table -
i have code (see below) populates table records. want replace id presented site_id actual name stored in table. site_id
example primary key in table called sites_tbl
, , want pull associated sitename
, display in table rather id comes sheets_tbl
foreign key. assume need kind of loop, foreach site_id within $data variable select sitename site_id = $row['site_id']
cannot work.
$sql = "select * sheet_tbl"; $stmt = $conn->prepare($sql); $stmt->execute(); $data = $stmt->fetchall(); <?php foreach ($data $row): ?> <tr> <td><?=$row['sheet_id']?></td> <td><?=$row['username']?></td> <td><?=$row['site_id']?></td> </tr>
i advise simple sql join. assuming site name sitename
in sites_tbl:
$sql = "select sheet.sheet_id, sheet.username, site.sitename 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 $row): ?> <tr> <td><?=$row['sheet_id']?></td> <td><?=$row['username']?></td> <td><?=$row['sitename']?></td> </tr>
so not have data sheet_tbl
associated data sites_tbl
can use directly.
read more joins here: http://www.w3schools.com/sql/sql_join.asp
Comments
Post a Comment