2 columns on a left join - php

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.

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

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

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

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)

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

Related

Getting information from multiple using MySQLI and be able to echo results

for the past few hours, I have been trying to find a simple method of while loop echoing information from multiple tables at once. I'd like to say I've not pulled all my hair out looking, but I have.
Here is one mysqli query to get the following fields from CUSTOMER
$tid = $_SESSION['user_id']; // "id" is 1 for example
$query = "SELECT * FROM `CUSTOMER` WHERE user_id = {$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['user_id'] . "<br><br>";
echo $row['c_fname'] . "<br>";
echo $row['c_sname'] . "<br>";
};
Here is another mysqli query to get the following fields from SALE
$query = "SELECT * FROM `SALE` WHERE user_id = {$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['s_date'] . "<br>";
echo $row['s_total'] . "<br>";
};
Could someone possibly show me how I can get both of these tables in one query so that echoing both tables information is possible at the same time instead of separately. I am not fussed how it is done, As long as it gets all from both tables for echoing purpose, that is good.
You can do it by using LEFT JOIN like this.
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
And this is your code.
$query = "SELECT * FROM `CUSTOMER` LEFT JOIN `SALE` ON `SALE`.user_id=`CUSTOMER`.user_id WHERE `SALE`.user_id={$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['user_id'] . "<br><br>";
echo $row['c_fname'] . "<br>";
echo $row['c_sname'] . "<br>";
echo $row['s_date'] . "<br>";
echo $row['s_total'] . "<br>";
}
For more info read this,
https://www.w3schools.com/sql/sql_join_left.asp
I hope this helps.
EDITED
This is for joining 3 tables,
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
LEFT JOIN table3 ON table1.column_name = table3.column_name;
In your code.
SELECT * FROM `CUSTOMER`
LEFT JOIN `SALE` ON `CUSTOMER`.user_id = `SALE`.user_id
LEFT JOIN `PRODUCTS` ON `CUSTOMER`.user_id = `PRODUCTS`.user_id
WHERE `SALE`.user_id={$tid};
As variable.
$query = "SELECT * FROM `CUSTOMER` LEFT JOIN `SALE` ON `CUSTOMER`.user_id = `SALE`.user_id LEFT JOIN `PRODUCTS` ON `CUSTOMER`.user_id = `PRODUCTS`.user_id WHERE `SALE`.user_id={$tid}";
You can use the following code and will help u solve Ur problem
$query = "SELECT C.*,S.* FROM CUSTOMER C,SALES S
WHERE C.user_id={$tid}
and C.user_id=S.user_id;
while ($row = mysqli_fetch_array($results)) {
echo $row['C.user_id'] . "<br><br>";
echo $row['C.c_fname'] . "<br>";
echo $row['C.c_sname'] . "<br>";
echo $row['S.s_date'] . "<br>";
echo $row['S.s_total'] . "<br>";
};
You can simply join the tables to get your expected result as shown below.
$query = "SELECT c.user_id, c.c_fname, c.c_sname, s.s_date, s.s_total FROM `CUSTOMER` AS c INNER JOIN `SALE` AS s ON c.user_id = s.user_id WHERE c.user_id = {$tid}";
Joining 3 tables example
$query = "SELECT *
FROM `CUSTOMER` AS c
INNER JOIN `SALE` AS s ON c.user_id = s.user_id
INNER JOIN `PRODUCTS` AS p ON p.product_id = s.product_id
WHERE c.user_id = {$tid}";

How to echo values from another table?

Hello I have 2 tables named tbl_guard and tbl_records. The tbl_guard has columns guard_id and fullname, while tbl_records has guard_id also. And here is my code:
$query = "SELECT * FROM tbl_records";
$stmt = $dbc->prepare($query);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row);
echo "<table>";
echo "<tr>";
echo "<td>Name</td>";
echo "</tr>";
echo "<tr>";
echo "{$guard_id}";
echo "</tr>";
}
echo "</table>";
What I want to do is instead of the guard_id being echoed there in the loop, I want the fullname in the tbl_guard table.
Your help would be very much appreciated!
Use JOIN
$query = "SELECT tbl_records.*, tbl_guard.fullname FROM tbl_records LEFT
JOIN tbl_guard ON tbl_guard.guard_id = tbl_records.guard_id";
In PHP
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
.
.
.
echo "{$fullname}";
}
What you want to achieve seems to be a foreign key relation - you have to use JOINS. In your example:
SELECT r.*, g.fullname FROM tbl_records r LEFT JOIN tbl_guard g ON r.`guard_id`=g.`guard_id`
Read MySQL documentation, you will need this more often!
I got it working already, here is my sql query:
SELECT tbl_records.*, tbl_residents.fname, tbl_residents.lname FROM tbl_records LEFT JOIN tbl_residents ON tbl_residents.stud_id = tbl_records.stud_id
Thanks everyone!

Display selected results only from the database table

I would like to display only a selected result on my php page.
This is my php code:
$bookdetsql = "
SELECT b.bookISBN
, b.bookTitle
, b.bookYear
, b.catID
, b.pubID
, p.pubName
, p.location
, c.catDesc
, b.bookPrice
FROM nbc_book b
LEFT
JOIN nbc_category c
ON b.catID = c.catID
LEFT
JOIN nbc_publisher p
ON b.pubID = p.pubID
";
$bookdetrs = mysqli_query($conn, $bookdetsql) or die(mysqli_error($conn));
$bookdetnum = mysqli_num_rows($bookdetrs);
if($bookdetnum >= 1 ){
echo "<div style='margin: 0 0 10px 0; font-weight: bold;'>$bookdetnum record(s) found!</div>";
while ($row = mysqli_fetch_assoc($bookdetrs)) {
echo "<tr>";
echo "<td><center>" . $row['bookTitle']."</a></center></td>";
echo "<td><center>" . $row['bookYear']."</center></td>";
echo "<td><center>" . $row['catDesc']."</center></td>";
echo "<td><center>" . $row['bookPrice']."</center></td>";
echo "<td><center>" . $row['pubName']."</center></td>";
echo "<td><center>" . $row['location']."</center></td>";
echo "</tr>";
}
} else {
echo "<b>Books not found!</b>";
}
Actually this code above is displaying the whole list of records actually. I only want it to display selected record which i clicked on my first php page.
How did you get the values frmo the first page? GET or POST?
when you have the value(s), you can add an where clause to your SELECT Statement
$bookdetsql = "SELECT bookISBN, bookTitle, bookYear, nbc_book.catID, nbc_book.pubID, pubName, location, catDesc, bookPrice
FROM nbc_book
LEFT JOIN nbc_category ON nbc_book.catID = nbc_category.catID
LEFT JOIN nbc_publisher ON nbc_book.pubID = nbc_publisher.pubID
WHERE bookISBN = '" . $_GET["bookISBN"] . "'";
Pleas Replace left join to join because left join is fetch matching and unmatch both record but when you use simple join it is work on inner join and fetch only match record according to your requirement
$bookdetsql = "SELECT bookISBN, bookTitle, bookYear, nbc_book.catID, nbc_book.pubID, pubName, location, catDesc, bookPrice FROM nbc_book JOIN nbc_category ON nbc_book.catID = nbc_category.catID JOIN nbc_publisher ON nbc_book.pubID = nbc_publisher.pubID";
$bookdetrs = mysqli_query($conn, $bookdetsql) or die(mysqli_error($conn));
$bookdetnum = mysqli_num_rows($bookdetrs);
if($bookdetnum >= 1 ){
echo "<div style='margin: 0 0 10px 0; font-weight: bold;'>$bookdetnum record(s) found!</div>";
while ($row = mysqli_fetch_assoc($bookdetrs)) {
echo "<tr>";
echo "<td><center>" . $row['bookTitle']."</a></center></td>";
echo "<td><center>" . $row['bookYear']."</center></td>";
echo "<td><center>" . $row['catDesc']."</center></td>";
echo "<td><center>" . $row['bookPrice']."</center></td>";
echo "<td><center>" . $row['pubName']."</center></td>";
echo "<td><center>" . $row['location']."</center></td>";
echo "</tr>";
}
} else {
echo "<b>Books not found!</b>";
}

Connect PHP pages in dreamweaver to MySQL queries

I'm trying to connect a series of five select menus created on Dreamweaver to generate one result through this query below. I keep getting errors every time I run the query. This is the query I have on my PHP page:
enter code here
<?php
$connect= mysql_connect("localhost","root", "password");
// Check connection
if (!mysql_select_db('db_name', $connect)) {
echo 'Could not select database';
exit;
}
$sql = "SELECT SER_ID and ser_type FROM services
INNER JOIN service_type ST
ON s.SER_ID= st.SER_ID
inner join profile P
on st.P_ID = p.P_ID
inner join room_services rs
on rs.SER_ID = s.SER_ID
inner join room r
on r.R_ID = rs.R_ID
inner join room_sensor rse
on rse.R_ID = r.R_ID
inner join sensor sen
on sen.S_ID = rse.S_ID
inner join service_sensor ss
on ss.SER_ID = s.SER_ID
inner join services_conditions sc
on sc.SER_ID = s.SER_ID
inner join conditions c
on c.C_ID = sc.C_ID
where p.username = Adam
AND sen.sensor_type = motion detector";
$result= mysql_query($sql, $connect);
echo "<table border='1'>
<tr>
<th>ser_ID</th>
<th>service_Type</th>
</tr>";
while($row = mysql_query($result)) {
echo "<tr>";
echo "<td>" . $row['ser_ID'] . "</td>";
echo "<td>" . $row['service_Type'] . "</td>";
echo "</tr>";
}
echo "</table>";
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['ser_ID'];
echo $row['serice_Type'];
}
mysql_free_result($result);
mysql_close($connect);
?>
enter code here
enter code here
The error I keep receiving is:
DB Error, could not query the database MySQL Error: Query was empty
This is happening despite the fact that the query is running completely fine on phpMyAdmin.
Any help appreciated.

php table warning : Invalid argument supplied for foreach

I want to output a 5 column table based on the query below , the output on phpmyadmin is correct but I am getting error :
Invalid argument supplied for foreach() on the php page. Any help would be highly appreciated. Thanks
code :
<?php
$database =& JFactory::getDBO();
//Declare Variables
$user = JFactory::getUser();
$id = $user->get('id');
$name = $user->get('name');
// Display quizzes
echo "</br>";
echo "Quizzes History for : " ;
echo "<b>";
echo $name;
echo "</b>";
echo "</br>";
echo "</br>";
$database->setQuery(" SELECT distinct qui.title AS name,
( SELECT GROUP_CONCAT(profiles.title)
FROM jos_jquarks_users_profiles AS users_profiles
LEFT JOIN jos_jquarks_profiles AS profiles ON users_profiles.profile_id = profiles.id
WHERE users_profiles.user_id = sessionWho.user_id ) AS profile,
( SELECT sum(score)
FROM jos_jquarks_quizzes_answersessions
WHERE quizsession_id = quizSession.id AND status <> -1 ) AS score,
( SELECT count(distinct question_id) FROM jos_jquarks_quizzes_answersessions
WHERE quizsession_id = quizSession.id ) AS maxScore,
DATE_FORMAT(quizSession.finished_on,'%M %d, %Y') AS FinishedOn
FROM jos_jquarks_quizsession AS quizSession
LEFT JOIN jos_jquarks_users_quizzes AS users_quizzes ON users_quizzes.id = quizSession.affected_id
LEFT JOIN jos_jquarks_quizzes AS qui ON users_quizzes.quiz_id = qui.id
LEFT JOIN jos_jquarks_quizzes_answersessions AS quizSessAns ON quizSessAns.quizsession_id = quizSession.id
LEFT JOIN jos_jquarks_sessionwho AS sessionWho ON sessionWho.session_id = quizSession.id
LEFT JOIN jos_jquarks_users_profiles AS users_profiles ON users_profiles.user_id = sessionWho.user_id
LEFT JOIN jos_jquarks_profiles AS profiles ON profiles.id = users_profiles.profile_id
WHERE sessionWho.user_id = ' .$id " ) ;
if (!$database->query()) { //write data and if error occurs alert
echo "<script> alert('".$database->getErrorMsg()."'); </script>";
}
//var_dump($database);
$tableStyle = "padding: 5px;border:1px";
$tdStyle = "padding:5px ";
$thStyle = "padding:7px ";
echo '<table style="' . $tableStyle . '" cellpadding="7" cellspacing="7">';
echo "<tr> <th style=align:center>Quiz Title </th><th style=align:center> Score </th><th>Maximum Score </th><th> Unanswered </th> <th>Finished On </th></tr>";
$row = $database->loadRowList();
foreach($row as $valuearray)
{
echo '<tr style=" align="center">';
foreach($valuearray as $field)
{
echo "<td>$field</td>";
}
echo "</tr>";
}
echo "</table>";
?>
This typically means that there is an error in your query, and it's not returning any results so there is no object to run through the foreach. The easiest way to debug this is to turn on debug mode from the joomla administrator panel (it's in global settings -> system), and then going to the page this error is being thrown, and it should show the SQL error.
Anyway, looking at the query the only error I can find (assuming all fields/tables are correct) is that at the end you have:
WHERE sessionWho.user_id = ' .$id " ) ;
This should be:
WHERE sessionWho.user_id = $id " ) ;
or
WHERE sessionWho.user_id = ". intval($id) ) ;

Categories