MySql combining two columns from 2 tables using UNION - php

I would like to take 2 tables from a MySql database and output 2 specific column's from each table and combine the values of the columns into a regular table of 4 columns using the UNION statement to weed through the duplicates.
I have 2 tables one is called (tblproducts) and the other (tblpricing)
There are 2 columns in each of the tables i want to display their values into a regular table.
(tbleproducts)
->name <-this is a column of product names
->description <- this is a column of descriptions of each product
(tblpricing)
->monlthy <--this is the monthly price
->annually <--this is the yearly price
You can see the tables displaying here
MY only problem is this code below, the Yearly and monthly does not display, just the name and description.
I have renamed the JOINS to opposite of each other and they will display the values of YEARLY and MONTHLY but in the wrong columns, so i know it is not the echo table code that is the problem. Its the order of wi
if ($result = $conn->query("SELECT tblproducts.description, tblproducts.name
FROM `tblpricing` RIGHT JOIN `tblproducts` on annually = tblproducts.id
UNION SELECT tblpricing.monthly, tblpricing.annually
FROM `tblproducts` LEFT JOIN `tblpricing` on monthly = tblpricing.id; "))
echo "<tr>";
echo "<td>" . $row->name . "</td>";
echo "</tr>";
(tbleproducts)
name
description
(tblpricing)
monthly
yearly
below are some links to pictures to help you.
Picture of both databases and oy complete code

Related

How to add column if 2 other field is same [duplicate]

Building an inventory system. I have lots of products and each product has three different variables. So for stock totals I want to group by the two columns (product & size) and sum quantity to get stock total.
product
Size
Quantity
Widget one
2
275
Widget one
2
100
Widget two
3
150
Widget two
2
150
What I want for output:
product
Size
Quantity
Widget one
2
375
Widget two
3
150
Widget two
2
150
I figured out how to group by one column and sum using the code below:
$query = "SELECT product, SUM(Quantity) FROM inventory GROUP BY product";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total ". $row['product']. " = ". $row['SUM(Quantity)'];
echo "<br />";
}
?>
I am just stuck on grouping by both columns. Is it possible? or should I just create three different products for the of the three sizes and eliminate that column? Thanks.
Based on your example table, it appears you want to be grouping on product rather than id. You merely need to add the Size column to both the SELECT list and the GROUP BY
$query = "SELECT
product,
Size,
SUM(Quantity) AS TotalQuantity
FROM inventory
GROUP BY product, Size";
Note that I have added a column alias TotalQuantity, which will allow you to more easily retrieve the column from the fetched row via the more sensible $row['TotalQuantity'], rather than $row['SUM(Quantity)']

Echo data from two different mysql tables using php

I'm trying to display data from two different mysql tables on my website using php.
My aim is to display a match schedule with information from two tables. The first one includes all the teams plus their ID, the second includes all details on the games. I now want to "replace" the "home_id" and "away_id" fields with the respective team names from the first table.
The tables look as follows:
table "teams"
id name
-----------
1 Team 1
2 Team 2
3 Team 3
4 Team 4
...
table "matchschedule"
id home_id away_id goals_home goals_away date
1 1 2 0 2 2016-05-05
2 3 4 2 1 2016-05-06
...
With the following query I'm getting the required data within phpmyadmin:
SELECT
date, home.name, sp.goals_home, away.name, sp.goals_away
FROM
matchschedule sp
INNER JOIN
teams home on sp.home = home.id
LEFT JOIN
teams away on sp.away = away.id
However, when I implement this query into my website and add the code below to display the data the fields "home.name" and "away.name" are always empty. What do I need to change in order to get the team names displayed?
while($row = mysql_fetch_array($query)) {
?>
<table border=1>
<tr>
<?php
echo "<td>".$row['date']."</td>";
echo "<td>".$row['home.name']."</td>";
echo "<td>".$row['goals_home']."</td>";
echo "<td>".$row['away.name']."</td>";
echo "<td>".$row['goals_away']."</td>";
?>
</tr>
</table>
Final result (with missing info for both team names):
2016-05-05 [] 0 [] 2
2016-05-06 [] 2 [] 1
The issue is that when in query you request home.name mysql return to php column with title name and you can not reach that column using home.name anymore. And same for away.name.
That's why you need to set proper name for returned columns.
Change your query to:
SELECT
date, home.name home_name, sp.goals_home, away.name away_name, sp.goals_away
FROM
matchschedule sp
INNER JOIN
teams home on sp.home = home.id
LEFT JOIN
teams away on sp.away = away.id
and call those columns in php like:
echo "<td>".$row['date']."</td>";
echo "<td>".$row['home_name']."</td>";
echo "<td>".$row['goals_home']."</td>";
echo "<td>".$row['away_name']."</td>";
echo "<td>".$row['goals_away']."</td>";
Based on your table strcture, you should do the following :
SELECT
date, home.name AS homeName, sp.goals_home, away.name AS awayName, sp.goals_away
FROM
matchschedule sp
INNER JOIN
teams home on sp.home_id = home.id
LEFT JOIN
teams away on sp.away_id = away.id
So basically replace sp.home by sp.home_id and sp.away by sp.away_id and change the fields name as you have the same fields name in your tables.

Populate select drop down with data from two mysql queries

I'm sure this is easy to figure out to most anyone who knows PHP and mysql but I am not able to figure it out. I will try to explain in the best way possible
Please let me know if I'm miss something
Relevant Table structure
Table | Fields
category | id,group_n (more fields exist but are not required now)
p_group | id,group_n
what I want to achieve:
Query to find currently selected group_n field in category table if available based on the current _isset id taken from the _get URL in relation to the category.
Example of work flow :
sample rows for category
ID | category | short | group_n
1 | Skin Whitening Pills | pills | Skin Whitening
2 | Skin Whitening Cream | cream | Skin Whitening
3 | Weight Gain / Loss | wgainl | Weight Gain / Loss
As you can see multiple categories can have a single group_n. I use the group_n to show an expert for that group.
select option is populated with the field group_n from category
select options are populated with all options from p_group (except selected so there is no duplicate"
category with id 2 has group_n as Skin Whitening
edit_category.php?id=2 would display all input options for for id 2 that are currently in the table row in order to edit them and update the query. Now when the select options for the group_n are populated the selected should be Skin Whitening but all rows in p_group should be available to select.
code
<?php
$qry=mysql_query("SELECT group_n from category where id=$id", $con);
if(!$qry)
{
die("Query Failed: ". mysql_error());
}
?>
<select name="group" id="group">
<?php
// First, define the desired default value
$default_value = $row['group_n'];
while($row=mysql_fetch_array($qry))
{
// Then you can mark that one as selected in your "while" loop
$selected = ($row['group_n'] == $default_value) ? ' selected' : '';
$qry2=mysql_query("SELECT * from p_group", $con);
while ($row2 = mysql_fetch_array($qry2))
{
echo "<option value='" . $row2['group_n'] . "'" . $selected . ">" . $row2['group_n'] . "</option>";
}
}
?>
</select>
I've also tried with a single query left joining the two tables but the following query will list only a single row which doesn't get auto populated but gives the right value.
$qry=mysql_query("
SELECT a.group_n,
b.group_n from p_group a
left join category b
on a.group_n=b.group_n
group by b.group_n where b.id=$id", $con);
I am not sure whether my query needs to be changed or the php but I can only get one of the queries to work with the select at a single time. I need to know how to get either both queries to work so selected option is one from the category table and the drop down from p_group table.
Ideally I would want the category table to be associated with the id from p_group but for now I'd settle for keeping it as text.
After waiting for input from the user community which is unusually quiet this week, I searched around and fiddled with code until I came to the UNION sql join. This basically takes two sets of data and presents as one which did the trick. Not sure if this is the best way and maybe there is a pure PHP way, but this did the trick.
SQL snippet
$qry=mysql_query("select group_n as group_a from category where id=$id union select group_n from p_group group by group_n", $con);
Basically this would select query on left union it with the query on the right and display all the records.
Limitations
1. field count selected must match
2. UNION will select no duplicates
3. UNION ALL will select duplicates
full relevant code :
$qry=mysql_query("select group_n as group_a from category where id=$id union select group_n from p_group group by group_n", $con);
if(!$qry)
{
die("Query Failed: ". mysql_error());
}
// First, define the desired default value
$default_value = $row['group_a'];
while($row=mysql_fetch_array($qry))
{
$selected = ($row['group_a'] == $default_value) ? ' selected' : '';
// Then you can mark that one as selected in your "while" loop
echo "<option value='" . $row['group_a'] . "'" . $selected . ">" . $row['group_a'] . "</option>";
}
?>
</select>

MySQL: Group by two columns and sum

Building an inventory system. I have lots of products and each product has three different variables. So for stock totals I want to group by the two columns (product & size) and sum quantity to get stock total.
product
Size
Quantity
Widget one
2
275
Widget one
2
100
Widget two
3
150
Widget two
2
150
What I want for output:
product
Size
Quantity
Widget one
2
375
Widget two
3
150
Widget two
2
150
I figured out how to group by one column and sum using the code below:
$query = "SELECT product, SUM(Quantity) FROM inventory GROUP BY product";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total ". $row['product']. " = ". $row['SUM(Quantity)'];
echo "<br />";
}
?>
I am just stuck on grouping by both columns. Is it possible? or should I just create three different products for the of the three sizes and eliminate that column? Thanks.
Based on your example table, it appears you want to be grouping on product rather than id. You merely need to add the Size column to both the SELECT list and the GROUP BY
$query = "SELECT
product,
Size,
SUM(Quantity) AS TotalQuantity
FROM inventory
GROUP BY product, Size";
Note that I have added a column alias TotalQuantity, which will allow you to more easily retrieve the column from the fetched row via the more sensible $row['TotalQuantity'], rather than $row['SUM(Quantity)']

PHP Mysql trying to pull multiple rows from different tables (works for 3 rows on 2 tables but not 4 rows from 3 tables)

I'm trying to pull multiple rows from different tables in a database.
If I only have the first 3 rows from two tables, it works fine. As soon as I add the third table and try and pull another row it breaks!
Ultimately what I'm trying to do is pull the image, the dayid, the name of a person, and then name of a cause.
The imageURL and the Outfitday_id are in the same table, the name of the person is in the table Pilot, and the name of the cause is in the table cause.
For some reason it will pull the first two rows (imageUrl, outfitDay_id) from the table Outfitimage, then pull the 3rd row (name) from Pilot, but fails if I add the name and try and pull it from the Cause table.
$link = mysql_connect("host","user","pass");
if ($link) {
mysql_selectdb("up",$link);
// Select records from the DB
$query = "SELECT imageUrl,outfitDay_id,name,name FROM OutfitImage,Pilot,Cause ORDER BY Rand(" . date("Ymd") . ") LIMIT 1";
$image = mysql_query($query);
// Display records from the table
echo "";
while ($row = mysql_fetch_array($image, MYSQL_NUM)) {
echo "<IMAGE SOURCE='$row[0]'/><br>";
echo "<div id='info'>Day $row[1] of ";
echo "$row[2] Uniform Project for$row[3] </div>";
}
echo "";
} else {
echo "Can't connect to the database!";
}
It probably happens because the name column is ambiguous. I'm guessing you have a name column in both the Cause and Pilot (or some other table). MySQL can't guess what table you want to retrieve the column value from, and will spit an error (Column name in field list is ambiguous).
Make sure you prefix the column name with the table name to remove ambiguity:
SELECT
imageUrl, outfitDay_id, Cause.name, Pilot.name
FROM
OutfitImage, Pilot, Cause
You are attempting a cross-join across all three tables, but you aren't creating any conditions to filter them out. The clause FROM table1, table2, table3 attempts a cross-join across all three tables. A cross-join means every row from one table is paired up with every row from another table. For example, say I have three tables, each have two rows. The first table I call names with the two rows jack and jill, the second table I will call ages with rows 21 and 24, the third table will be genders, and have rows male and female. If I do a clause FROM names, ages, genders, it will return a table with 2 X 2 X 2 = 8 rows.
names ages genders
jack 21 male
jack 21 female
jack 24 male
jack 24 female
jill 21 male
jill 21 female
jill 24 male
jill 24 female
Normally, when you cross-join, you also add a condition to WHERE to filter out rows that don't make sense. For example, from example FROM clause you might have a WHERE genders.id = names.genders_id. In this case, you are linking a name with a specific gender row from the genders table. This will probably also solve your need for a LIMIT 1.

Categories