Get value of another column based on foreign key - php

I am displaying all data from a table in a view for the administrator in a web app.
The SQL looks something like this:
$organizations = $db->query("
SELECT id, organization_name, owner_id
FROM organizations
ORDER BY created_on DESC
")->fetchALL(PDO::FETCH_ASSOC);
The part of the view I am working with is as follows:
<?php foreach($organizations as $organization): ?>
<tr>
<td><?php echo e($organization['organization_name']); ?></td>
<td><?php echo e($organization['owner_id']); ?></td>
</tr>
<?php endforeach; ?>
This works exactly as expected but is not actually what I want to display as far as the owner_id (an int and the primary key of the users table)
This will generate a table with all the values as in the SQL statement and in particular it will render the owner_id to the view which is a foreign key related to my users table.
What I want to do is actually display the name of the owner that belongs to the owner_id instead of just showing the id (i.e... 32). How can I display the associated name of the user from the users table based on the foreign key user_id that is referenced?

You need to use a JOIN to link the two tables. The example below links the two tables on owner_id and includes the user_name in the result. You will need to use an alias in the SELECT in the case that any of the column names exist in both tables.
-- use alias and include user_name
SELECT o.id, o.organization_name, u.user_id, u.user_name
-- alias the table as "o"
FROM organizations o
-- alias the table as "u"
JOIN users u
-- link the tables here on owner_id
ON o.owner_id = u.user_id
ORDER BY o.created_on DESC
You can then output the value of the user_name column in your PHP like so:
<td><?php echo e($organization['user_name']); ?></td>

You can use JOIN.
$organizations = $db->query("
SELECT organizations.id, organizations.organization_name,
users.user_name
FROM organizations
JOIN users ON organizations.owner_id = users.user_id
ORDER BY organizations.created_on DESC
")->fetchALL(PDO::FETCH_ASSOC);
Then in view, it can be used as
<?php foreach($organizations as $organization): ?>
<tr>
<td><?php echo e($organization['organization_name']); ?></td>
<td><?php echo e($organization['user_name']); ?></td>
</tr>
<?php endforeach; ?>

Related

Join Two MySQL Table and Display Result in Table

I have two table called t_user and t_chat. I am trying to display message from t_chat in PHP table like below.
$quotes_qry="SELECT * FROM t_chat ORDER BY id DESC LIMIT $start, $limit";
$result=mysqli_query($mysqli,$quotes_qry);
<?php
$i=0;
while($row=mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo ++$sr+$start;?></td>
<td><?php echo $row['sender'];?></td>
<td><?php echo nl2br($row['receiver']);?></td>
<td><?php echo nl2br($row['message']);?></td>
<td><?php echo time_elapsed_string($row['time']);?></td>
<td><img src="images/delete-icon.png"></td>
</tr>
<?php
$i++;
}
?>
I want display sender and receiver name which is located in table called t_user with username column. I am new in PHP and confused how can I achieve it. Let me know if someone can help me for achieve my task. Thanks a lot!
Note : t_chat table have userid witch column name called sender and receiver, currently I am displaying that userid in above table, instead I want display username.
Thanks
The joins might look something like this:
SELECT t_chat.sender AS 'sender', t_chat.receiver AS 'receiver', t_chat.message AS 'message', t_chat.time AS 'time', t_chat.id AS 'id', user1.username AS 'senderusername', user2.username AS 'receiverusername'
FROM t_chat
LEFT JOIN t_user AS user1 ON t_chat.sender = user1.id
LEFT JOIN t_user AS user2 ON t_chat.receiver = user2.id
ORDER BY id DESC
In this example I am joining the tables twice (as user1 and user2) so that the t_user table gets referenced independently for each lookup.
I also gave each column a name using AS to make them easier to reference later in your code.
Try this sql (The t_user table must have an id column that matches the userid from t_chat):
$quotes_qry="SELECT t1.sender, t1.receiver, t1.message, t1.time, t2.username FROM t_chat AS t1 INNER JOIN t_user AS t2 ON t1.userid=t2.id ORDER BY t1.id DESC LIMIT $start, $limit";
More details and examples about MySQL JOIN you can find in the tutorial from:
https://coursesweb.net/php-mysql/mysql-inner-left-join-right-join_t

select top 5 sellers in mysql

I have the follow table in MySQL
TABLE "SALES"
id, product, code, quantity, amount, who-sold-it
while the field "who-sold-it" is just a example to understand the question but not the real name of the field
Now I have another table the name is "USERS" and it looks like this
id, name, sellercode
I need to get the top 5 sellers using the 2 tables looking the who-sold-it in each SALE and display their name and sold amounts
Order the results by total sales and take the top 5 with limit. You can also join the sales table with the seller table to get the name of the seller.
select users.name, users.sellercode, sum(sales.amount) as total
from sales, users
where sales.sellercode = users.sellercode
group by users.sellercode, users.name
order by total desc
limit 5
To display the result:
<?php while ($row = mysqli_fetch_assoc($result)) ?>
<tr>
<td><?php echo htmlspecialchars($row['name'])</td>
<td><?php echo htmlspecialchars($row['total'])</td>
</tr>
<?php } ?>

Fetching MySQL via their foreign keys

This one is a tough one to crack for me personally
My dilemma is:
I have 3 InnoDB table in my database called "order_detail", "orders", "billing" with the following structure:
The table "order_detail" looks like this:
•orderid (foreign key pointing to a serial in a table called "orders")
•productid (foreign key pointing to the serial in a table called "products")
•quatity (type INT)
•price (type FLOAT)
The table "orders" looks like this:
•serial (primary key, auto_increment)
•date (type DATE)
•customerid (type INT(11)) (foreign key pointing to the serial in a table called "billing")
•total (type FLOAT)
The table "billing" looks like this:
•serial (primary key, auto_increment)
•name (type VARCHAR(25))
•userid (type VARCHAR(25))
I have a PHP file with the aim to simply print out a description of the orders placed, e.g.:
Order ID | Product ID | Amount | Quantity | Total | Date Ordered
Now, I simply want to use the userid, call my database (only the "billings" table) and be able to get the serial, date and total from the "orders" and from their onwards to get the productid, quantity and price from the "order_detail" table.
Right now, my non-working code looks like this:
<?php
require("includes/config.php");
$users_query=mysql_query("SELECT * FROM billing WHERE userid='$username'");
$row=mysql_fetch_array($users_query);
?>
<table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%">
<?php {
echo '<tr bgcolor="#FFFFFF" style="font-weight:bold"><td>Order ID</td><td>Product ID</td><td>Amount</td><td>Quantity</td><td>Total</td><td>Date Ordered</td></tr>';
?>
<tr bgcolor="#FFFFFF">
<td><?php echo $row['serial']; ?></td>
<td><?php echo $row['productid']; ?></td>
<td><?php echo $row['price']; ?></td>
<td><?php echo $row['quantity']; ?></td>
<td><?php echo $row['total']; ?></td>
<td><?php echo $row['date']; ?></td>
</tr>
<?php } ?>
</table>
(How) can I retrieve the columns mentioned without making separate calls to the "order_details" and "order" tables? When I check phpMyAdmin, the InnoDB foreign key links seem to work fine. Many thanks in advance!
Accessing foreign data can only be done using ORMs. They can inspect the DB structure and mine the data you need on the fly. In this case, they will handle the queries for you.
But i imagine you want / need to handle your data by hand the old way.
You can achieve this by making a joint query, like for example :
SELECT o.serial AS serial, d.productid AS productid, d.price AS price, d.quantity AS quantity, o.total AS total, o.date AS date
FROM order_detail d LEFT JOIN orders o ON o.serial = d.orderid LEFT JOIN billing b ON b.serial = o.customerid
WHERE b.userid = '$username';
By the way, one shouldn't store in a DB a value that can be calculated on the fly (example: the order.total column that is a SUM() of related prices and quantities).
In my own opinion, you shouldn't use hand made queries like this. It exposes you to SQL injection, data formatting / typing issues and such mess.
order_details(table)
order_detaild_id(primary key)
order_id(fkey from orders table)
quantity price
orders table
order_id
prod_id(fkey from products)
date
userid(fkey from billing)
total
billing table
billing_id(prmiary key)
serial
name
userid
orderid
here are some changes that need to be done to your database table schema
Query should look like this:
select
b.serials as serial, b.user_id as user_id, b.serial as serial_id, o.product_id as product_id,
od.price as price, od.quantity as quantity, o.total as total
from billings b
left join orders o
on o.order_id = b.order_id
left join order_details od
on od.order_id = o.order_id
where b.user_id = '.$userid.';`

php mysql selecting columns and compare with 3 values in different tables

I have 4 mysql tables holding interrelated data
playersTable
participationTable
hotelsTable
bookingsTable
I'm trying to retrieve the booking of players keeping in mind that some rooms might have 2 companions and some will not
MYSQL Tables physical design are structured at this way
playersTable
playerID
playerFullName
playerCountryID
participationTable
p_id
championshipId
playerId
countryId
status
booking_status
hotelsTable
hotelId
hotelName
championshipId
bookings
b_ID
player1_id
player2_id
hotelId
arrivalTime
What I'm trying to do is SELECT all bookings and list them in a table where it can show both players, number 1 and number 2.
I'm using this query to get the results:
SELECT bookingsTable.*, playersTable.*, participantsTable.*, hotelsTable.*
FROM bookingsTable
LEFT JOIN participationTable
ON bookings.player1_id= participants.p_id
LEFT JOIN playersTable ON participants.playerID = players.playerID
LEFT JOIN hotelsTable ON bookings.hotelId = hotels.hotelId
I'm only getting one player, so I added I added another query that chooses the player2_id but when looping through the results, I cannot get it to work correctly, but I can get the player2_id number and not the name.
This is my PHP code where it loads the results, a kind help is always appreciated.
<?php do { ?>
<tr>
<td><?php echo $row_booking_retrival['id']; ?></td>
<td><?php echo $row_booking_retrival['playerFullname']; ?></td>
<td><?php echo $row_booking_retrival['playerFullname']; ?></td>
<td><?php echo $row_booking_retrival['hotelName']; ?></td>
<td><?php echo $row_booking_retrival['arrivalDate']; ?></td>
<td><?php echo $row_booking_retrival['arrivalTime']; ?></td>
<td><?php echo $row_booking_retrival['departureDate']; ?></td>
<td><?php echo $row_booking_retrival['departureTime']; ?></td>
<td><?php echo $row_booking_retrival['Notes']; ?></td>
</tr>
<?php } while ($row_booking_retrival = mysql_fetch_assoc($booking_retrival)); ?>
Thanks in advance.
Find the physical design and intended results at this link.
http://s18.postimg.org/gjsx4frfd/example.jpg
Based off your table data and expected results in your image, your are looking for a query like
SELECT
b.b_id as BookingID,
p1.fullname as player1full,
p2.fullname as player2full,
h.hotelName as hotelname,
b.arrival as arrivalDate
FROM
bookingsTable b
LEFT JOIN
participationTable pT1 ON b.player1 = pT1.p_id
LEFT JOIN
participationTable pT2 ON b.player2 = pT2.p_id
LEFT JOIN
playersTable p1 ON pT1.playerID = p1.playerID
LEFT JOIN
playersTable p2 ON pT2.playerID = p2.playerID
LEFT JOIN
hotelsTable h ON b.hotelid = h.hotelId
This then returns the results-
SQL Fiddle - http://sqlfiddle.com/#!2/68cd27/2

Mysql count with descending with join and where clause ,two tables, limit?

Here i have implemented two tables (pages, pagestatistics).I need result for last five records using join from the those tables and also i need a count of cID field from second table (pagestatistics), i need that count result will be display in descending.
NOTE : Primary id is cID.
![pagestatistics][1]![pages][2]
<?php
$recentpageviews =mysql_query("SELECT Distinct(cID) FROM `pagestatistics` order by `pstID` desc limit 0,5");
$downloads=mysql_num_rows($recentpageviews);
$k=1;
$cid="";
while($views_values=mysql_fetch_array($recentpageviews))
{
$cid.=",".$views_values['cID'];
$k++;}
}
$explode =explode(",",$cid);
for($i=1;$i<count($explode);$i++)
{
$sql=mysql_query("select Distinct(a.cID),count(a.cID) as clicks,b.cFilename,a.date from pagestatistics as a left join pages as b on a.cID=b.cID where a.cID='".$explode[$i]."' order by a.cID desc");
$res=mysql_fetch_array($sql);
?>
<tr>
<td class='ccm-site-statistics-downloads-title'><?php echo $res['cFilename'];?></td>
<td class='ccm-site-statistics-downloads-title'><?php echo $res['clicks'];?></td>
<td class='ccm-site-statistics-downloads-title'><?php echo $res['date'];?></td>
</tr>
<?php }?>
How to display all records in descending order.
Thank in advance.
You can do it in this way just order by with your count separated with , in ORDER BY clause
$sql=mysql_query("select Distinct(a.cID),count(a.cID) as clicks,b.cFilename,a.date
from pagestatistics as a left join pages as b on a.cID=b.cID
where a.cID='".$explode[$i]."' order by a.cID,clicks desc");

Categories