How to echo values from another table? - php

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!

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}";

2 columns on a left join

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

MySQL SUM to PHP While Loop

I am not sure how to get the result of a Mysql SUM into your while loop THEN into a variable for displaying in an HTML table.
Firstly I pass a list of codes ie ("1111", "33311", "43433") to a HTML form textarea then implode those codes into a variable called $in. I then pass the list of codes (represented by $in) to my SQL Query.
Mysql Query
SELECT tbl1.code, tbl1.name, tbl1.cost, tble.price, tbl1.vat, sum(tbl2.onhand) as onhand
FROM tbl1
INNER JOIN tbl2 ON tbl1.code=tbl2.code
WHERE (tbl2.name='AC' OR tbl2.name='WH')
AND tbl1.code IN ($in)
NOTE The query works if I do this instead (without the SUM and brackets) BUT it still shows an empty table cell for $stock:
tbl1.vat, tbl2.onhand AS onhand
I am then attempting to pass the value of the Mysql SUM function to a variable, then display that value within a table with php echo.
PHP
$result = $mysqli->query($sql);
if ($result = mysqli_query($mysqli, $sql)) {
while($row = $result->fetch_array()) {
$code = $row['code'];
$name = $row['name'];
$cost = $row['cost'];
$price = $row['price'];
$vat = $row['vat'];
$stock = $row['onhand']; **Result from the Mysql SUM**
...........}
HTML TABLE
echo "<td>" . $name . " </td>";
echo "<td>" . $cost . " </td>";
echo "<td>" . $price . " </td>";
echo "<td>" . $vat . " </td>";
echo "<td>" . $stock . " </td>";
The Mysql query does work as I've tested it in Mac Terminal Mysql but when I attempt to replicate that in php, the $stock is not getting echoed to the table cell??
Cheers
I'm pretty sure your missing a group by in your sql. Maybe changing it to
SELECT tbl1.code, tbl1.name, tbl1.cost, tbl1.price, tbl1.vat, sum(tbl2.onhand) as onhand
FROM tbl1
INNER JOIN tbl2 ON tbl1.code=tbl2.code
WHERE (tbl2.name='AC' OR tbl2.name='WH') AND tbl1.code IN ($in)
GROUP BY tbl1.code, tbl1.name, tbl1.cost, tbl1.price, tbl1.vat
might work.
Also notice how I changed tble.price to tbl1.price since it looks like a typo
just wanna point out a fact...
hope you are aware that sum is an aggregate function...so using it without a group by clause will cause it to return a just a single row containing the sum total of all the records
SELECT tbl1.code, tbl1.name, tbl1.cost, tbl1.price, tbl1.vat, sum(tbl2.onhand) as onhand
FROM tbl1
INNER JOIN tbl2 ON tbl1.code=tbl2.code
WHERE (tbl2.name='AC' OR tbl2.name='WH') AND tbl1.code IN ($in)
GROUP BY tbl1.code, tbl1.name, tbl1.cost, tbl1.price, tbl1.vat

inner join query don't return any things

I have a php code that use a mySQL query in it.
tables users and conversation and main_profile have true values to select after this query but query return nothing.
$sqlQuer =
"SELECT `conversation`.from,`conversation`.text, `main_profile`.nik_name, `users`.id
FROM `conversation`
INNER JOIN `users` ON(`users`.username = `conversation`.to )
INNER JOIN `main_profile` ON(`users`.id = `main_profile`.user_id)
WHERE `conversation`.to = '".$to."'
AND `conversation`.read = '0'";
$result = mysql_query( $sqlQuer) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row[0] . "#TEXT#" . $row[1]. "#TEXT#" . $row[2] . "#CON#";
$ids[] = $row['id'];
}
any Idea ?
Query was solved with this change that First INNER JOIN changed to LEFT JOIN and second changed to RIGHT JOIN.

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.

Categories