Reputation: 13434
Hello so I have 2 tables. tbl_records
and tbl_guards
. On tbl_guards
I have guard_id and on tbl_records
I have guard_id
and guard_id_in
. And here is my current code:
try
{
$stat = "0";
$query = "SELECT rec.*, tbl_guard.fname, tbl_guard.lname
FROM tbl_records as rec
LEFT JOIN tbl_guard ON tbl_guard.guard_id = rec.guard_id
LEFT JOIN tbl_records ON tbl_records.guard_id_in = tbl_guard.guard_id
WHERE rec.stud_id=? AND rec.status=?";
$stmt = $dbc->prepare($query);
$stmt->bindParam(1, $_GET['id']);
$stmt->bindParam(2, $stat);
$stmt->execute();
echo "<table cellpadding='3' class='searchTbl'>";
echo "<thead>";
echo "<tr>";
echo "<th>Actual Date</th>";
echo "<th>Purpose</th>";
echo "<th>Destination</th>";
echo "<th>Exact TO</th>";
echo "<th>Expected TI</th>";
echo "<th>Guard</th>";
echo "<th>Actual TI</th>";
echo "<th>Guard IN</th>";
echo "</tr>";
echo "</thead>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$guard = $fname . " " . $lname;
echo "<tbody>";
echo "<tr>";
echo "<td>$act_date</td>";
echo "<td>$purpose</td>";
echo "<td>$destination</td>";
echo "<td>$exact_timeout</td>";
echo "<td>$exp_timein</td>";
echo "<td>$guard</td>";
echo "<td>$act_timein</td>";
echo "<td>$guard</td>";
echo "</tr>";
echo "</tbody>";
}
}
catch (PDOException $e)
{
echo "Error: " . $e->getMessage();
}
echo "</table>";
Here is tbl_records
data.
And here is tbl_guard
data.
Here is the current output.
My problem is it shows the same guard in guard_id
and guard_id_in
in my code.
Upvotes: 0
Views: 79
Reputation: 826
You should select twice the guard table and use aliases for your fields :
SELECT tr1.*, tg1.fname AS FNAME, tg1.lname AS LNAME,
tg2.fname AS FNAME_IN, tg2.lname AS LNAME_IN
FROM tbl_records AS tr1
LEFT JOIN tbl_guard AS tg1
ON tg1.guard_id = tr1.guard_id,
LEFT JOIN tbl_guard AS tg2
ON tg2.guard_id = trl.guard_id_in
then in PHP you'll have more vars : $FNAME, $LNAME, $FNAME_IN, $LNAME_IN
Upvotes: 1
Reputation: 2589
You can use LEFT JOIN
multiple times, like:
SELECT tbl_records.*, tbl_guard.fname, tbl_guard.lname
FROM tbl_records as rec
LEFT JOIN tbl_guard ON tbl_guard.guard_id = rec.guard_id
LEFT JOIN tbl_records ON tbl_records.guard_id_in = tbl_guard.guard_id
Upvotes: 4
Reputation: 1007
You can use:
SELECT tbl_records.*, tbl_guard.fname, tbl_guard.lname
FROM tbl_records
LEFT JOIN tbl_guard ON (tbl_records.guard_id OR tbl_records.guard_id_in) = tbl_guard.guard_id
Upvotes: 2
Reputation: 827
SELECT tr1
.*, tg1
.fname
, tg2
.lname
FROM tbl_records
AS tr1
LEFT JOIN tbl_guard
AS tg1
ON tg1
.guard_id
= tr1
.guard_id
,
LEFT JOIN tbl_guard
AS tg2
ON tg2
.guard_id
= trl
.guard_id_in
Upvotes: 1
Reputation: 826
Just to be sure, your tbl_records table can have a link to two different tbl_guards via guard_id and guard_id_in ?
Maybe you can try :
SELECT tbl_records.*, tbl_guard.fname, tbl_guard.lname FROM tbl_records LEFT JOIN tbl_guard ON tbl_guard.guard_id IN (tbl_records.guard_id, tbl_records.guard_id_in)
Upvotes: 1