Fetching MySQL via their foreign keys - php

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.';`

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 } ?>

Selecting * from two tables using php and mySQL [duplicate]

This question already has answers here:
How to resolve ambiguous column names when retrieving results?
(11 answers)
Closed 2 years ago.
I have two tables, one is projects, and the other is users.
PROJECTS table
ID | USER_ID | NAME
-------------------------------------
80 | 1 | ABC Co.
82 | 2 | XYZ Inc.
USERS table
ID | FIRSTNAME | LASTNAME
-------------------------------------
1 | Joe | Namath
2 | Jimmy | Fallon
What I want is to write a query such as:
SELECT * FROM PROJECTS, USERS WHERE PROJECTS.USER_ID=USERS.ID AND FIRSTNAME = "Joe"
I can successfully run the query in php, but when I attempt to access the results, I don't get what I want. I understand why, but I can't figure out a way to correct it. For example:
$row = mysqli_fetch_query($awesomeDatabaseLink);
echo $row['ID]; //returns '1' and I really wanted '80'
I get it. The two tables have fields with the same name, but it's not the same data. MySQL returns its best guess at what I so ambiguously asked for. However, I have also tried:
echo $row['PROJECTS.ID']; //returns an empty string.
I should mention that I desperately need "*" from both tables. The Projects table has dozens and dozens of fields (not my design, and re-engineering the database is out-of-scope). The Users table is also very extensive, so listing each field individually is much more impractical than it would appear by looking at my example tables.
Any suggestions?
SH
The quickest fix is to assign a unique column alias for the expression (in this case just a simple column reference).
When you do that, you will need to qualify the * with the table name or alias. If you want to return all of the columns from both tables, you will need to included a * for each table.
Also, ditch the old-school comma operator for the join operation, and use the JOIN keyword instead. And qualify all column references. For example:
SELECT PROJECTS.*
, USERS.*
, PROJECTS.ID AS MY_PROJECTS_ID
FROM PROJECTS
JOIN USERS
ON USERS.ID=PROJECTS.USER_ID
AND USERS.FIRSTNAME = "Joe"
The assigned alias MY_PROJECTS_ID will be the name of the column in the result set, so you reference that column by the assigned alias.
This assumes that there are no other columns being returned with the name MY_PROJECTS_ID.
Anytime there are two (or more) columns in the resultset that have the same name, you'll only get one of those columns referencing it by name.
I'd suggest you to use alias. That'd make things less ambiguous.
Try this:
SELECT
PROJECTS.ID AS project_id,
USER_ID,
NAME,
USERS.ID AS user_id,
FIRSTNAME,
LASTNAME
FROM PROJECTS, USERS
WHERE PROJECTS.USER_ID=USERS.ID AND FIRSTNAME = "Joe"
And then:
echo $row['project_id']; //returns Project id
Hope this helps.
When you select stuff from multiple tables you should always qualify the names (give the full path, like table.column). If two tables share a column name then you need to give them different names.
SELECT u.ID AS UserId,
u.FIRSTNAME AS FirstName,
u.LASTNAME AS LastName,
p.ID AS ProjectId,
p.NAME AS ProjectName
FROM USERS AS u
JOIN PROJECTS AS p ON p.USER_ID = u.ID
WHERE u.FIRSTNAME = "Joe"
If you want to get every column, but some of their names clash, then you can just rename the ones that clash, like so:
SELECT *,
u.ID as USERID,
p.ID as PROJECTID
FROM USERS AS u
JOIN PROJECTS AS p ON p.USER_ID = u.ID
WHERE u.FIRSTNAME = "Joe"
Hope this will help you.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Using single SQL</title>
<style>
table,td,th
{
padding:10px;
border-collapse:collapse;
font-family:Georgia, "Times New Roman", Times, serif;
border:solid #ddd 2px;
}
</style>
</head>
<body>
<table align="center" border="1" width="100%">
<tr>
<th>product id</th>
<th>product name</th>
<th>category name</th>
</tr>
<?php
mysql_connect("localhost","root");
mysql_select_db("dbtuts");
$res=mysql_query("SELECT c.* , p.* FROM tbl_categories c,tbl_products p WHERE c.cat_id=p.cat_id");
while($row=mysql_fetch_array($res))
{
?>
<tr>
<td><p><?php echo $row['product_id']; ?></p></td>
<td><p><?php echo $row['product_name']; ?></p></td>
<td><p><?php echo $row['cat_name']; ?></p></td>
</tr>
<?php
}
?>
</table>
</body>
</html>
follow this [link] (http://www.codingcage.com/2014/12/fetch-data-from-multiple-tables-in-php.html)!

Get value of another column based on foreign key

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; ?>

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

Categories