I am having an unexpected ton of difficulty trying to return all the currencies that a store accepts from the currency(banking) table.
The results I want should be:
Store name: Test
Store type: Grocery Store
Currency accepted: Bitcoin, Euros, Dollars
The results I get (when I remove GROUPBY Store) are:
Store name: Test
Store type: Grocery Store
Currency accepted: Bitcoin
Store name: Test
Store type: Grocery Store
Currency accepted: Euros
Store name: Test
Store type: Grocery Store
Currency accepted: Dollars
When I remove groupby store, then I only get the first result above (just the bitcoin result for currency)
There are 3 rows for the store id for currency, but it is only returning the first row's value (Bitcoin) since I am using GROUPBY and only one one result for the Test Store (But all 3 currencies for that store). I can't seem to get it to pull all 3 matching rows for the store id in that table into my results so that I get the 3 currencies returned.
I know the query is good from other tests, but I just don't know how to adjust the code below so that all currencies are returned and listed for the "Currency Accepted" table row on the page.
Here is the relevant code:
$query = "(
SELECT * FROM store
LEFT JOIN store_banking SB ON store.id=SB.store_id
LEFT JOIN banking B ON SB.banking_id = B.id
LEFT JOIN store_gaming SG ON store.id=SG.store_id
LEFT JOIN gaming G ON SG.gaming_id = G.id
WHERE
('$type' IS NULL OR '$type' = '' OR G.type = '$type')
And
('$currency' IS NULL OR '$currency' = '' OR B.currency= '$currency')
GROUP BY store.name
Order by store.name
)";
$result = mysqli_query($link, $query);
echo "<table border='1' cellpadding='5' cellspacing='5'>
<tr>
<th>Store Name</th>
<th>Type</th>
<th>Currency Accepted:</th> //need this to show all 3 matches; only showing 1
</tr>";
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row['currency'] . "</td>"; //only returns first results row :(
echo "</tr>";
}
/* free result set */
mysqli_free_result($result);
echo "</table>";
mysqli_close($link);
?>
I think a GROUP_CONCAT might do the trick for you.
And when you select with GROUP_CONCAT it's often best to set an alias on the select to easier reference it later.
For example:
SELECT GROUP_CONCAT(currency) as currency
Related
I have three tables:
Campaign
Customer
Office
As in the Campaign table the customer_id the same is as ID in the Customer table,
then he must show the customer_name also in Customer table.
Now he is showing the customer id with: $row->customer_id
I now have the following
if ($result = $mysqli->query("SELECT * FROM campaign ORDER BY campaign_id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->campaign_name . "</td>";
echo "<td>" . $row->customer_id . "</td>";
echo "<td>" . $row->office_id . "</td>";
echo "</tr>";
}
echo "</table>";
}
}
Thanks!
It's not incredibly clear what you're asking, but maybe try this query?
SELECT c.*, cust.* FROM campaign c, customer cust WHERE c.customer_id=cust.customer_id ORDER BY c.campaign_id
Using explicit (instead of implicit) JOINs, this query can be written as this:
SELECT c.*, cust.* FROM campaign c JOIN customers cust ON c.customer_id=cust.customer_id
As a note, I usually prefer to call out column names explicitly in queries, but since you didn't post your schema, I wasn't sure the names of your columns. Possibly something like this:
SELECT c.campaign_name, cust.customer_id FROM campaign c JOIN customers cust ON c.customer_id=cust.customer_id
Hi I want to create Categories listed which are saved in my database so when user upload his images and he select the category it saves the data in database in Cat column
Now I want to show category in PHP like this
Categories Total
Animals (4)
Celebrations (2)
Locations And Travel (11)
Object or still life (1)
Transportation (9)
Here is my PHP I am succeeded to show Categories names but not total category in each category
<?php
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"Select Cat from save_data Group By Cat ")
or die(mysql_error());
echo "<table border='1'>
<tr>
<th>Categories</th>
<th>Total</th>
</tr>";
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['Cat'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Extend the table cell:
<td colspan="2"></td>
This way it extends over another cell.
Also I notice you are mixing mysqli and mysql:
or die(mysql_error());
Try to use mysqli as objects and \Exceptions instead of errors. It's worth learning about :-)
Update:
I did not understand your question at first. Please provide your schema so we can see your table structure.
Usually you would have 2 tables, one with categories and one with data and join them with a GROUP BY (if an item can be in several categories, you would have a third table like category_has_item!):
SELECT c.category AS cat,
COUNT(i.items) AS num
FROM category c
LEFT JOIN items i
ON c.category_id = i.category_id
GROUP BY c.category
Use LEFT JOIN to display empty categories and JOIN (without LEFT) to avoid empty categories.
Change your table echo:
echo "<td>" . $row['cat'] . "</td><td>(" . $row['num'] . ")</td>";
Update:
If you only have 1 table, I strongly suggest you to read about database normalization.
Update your query:
Select Cat,COUNT(Data) AS num from save_data Group By Cat
Replace Data by your data column
and your echo line:
echo "<td>" . $row['Cat'] . "</td><td>(" . $row['num'] . ")</td>";
try to change your sql query like this
SELECT count(*) AS total_count FROM (SELECT Cat FROM save_data GROUP BY Cat HAVING COUNT(Cat) > 1) AS t
I have two databases. The first contains a list of upload doucuments and who they are for when uploaded and expiry date. This is stored as numbers representing each grade of person using implode. so column name 'foagrade' has 10,11,12 in row one. The second database is a list of grades and there ID's eg 10 = manager, 11 = HR etc. I am using left join and a basic html table to display a query.
$result = mysqli_query($con,
"SELECT UPLOAD.id, UPLOAD.title, UPLOAD.faoGrade,UPLOAD.faoLocation, UPLOAD.date, UPLOAD.expiry, GRADE.ID, GRADE.GRADE as GR, GRADE.id
FROM UPLOAD
LEFT JOIN GRADE ON
UPLOAD.faoGrade=GRADE.ID
where owner=$user");
echo "<table id='previous'>
<tr>
<th>Title/Document name:</th>
<th>For attention of Grade</th>
<th>For Location</th>
<th>date</th>
<th>Date expires</th>
<th>Delete this briefing</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
$id=$row['id'];
echo "<tr>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['GR'] . "</td>";
echo "<td>" . $row['foaLocation']."</td>";
echo "<td>" . date("D, d M Y ",($row['date']));
echo "<td>" . date("D, d M Y ",($row['expiry']));
echo "<td>delete</td> ";
echo "</tr>";
}
echo "</table>";
The query shows all the details but only shows the first grade stored in the column faograde (MANAGER) not 11 or 12.
How would I explode or split this? So for each number in this column a grade name is shown. i will also have to do the same for column 'faoLocation', but working on one issue at a time.
These tables should be normalized, but with what you have already you can do something like this:
SELECT UPLOAD.id as uploadID,
UPLOAD.title,
UPLOAD.faoLocation,
UPLOAD.date,
UPLOAD.expiry,
GRADE.ID as gradeID1,
GRADE.GRADE as GR,
GRADE.id as gradeID2 FROM UPLOAD, GRADE
WHERE
FIND_IN_SET(gradeID2,UPLOAD.faoGrade)
and UPLOAD.owner=$user;
Update
Here's the SQL Fiddle.
It is a bit confusing that there are multiple columns called id & ID. It's best to give them intuitive names like grade_ID or user_ID. From a normalization standpoint you could be using a relational table instead of the comma separated column (depending on how this data enters the database). Here's a video about normalization.
$comapre is an array with unique product ids passed on from previous page.so in the following page I want to look in the database using that productid, get information and compare the prices of the product corresponding to each productid from an array($compare).
So far I can display the relevant product information using productid from $compare(array) in the following format
productid | product name| price |
20______|__iphone5__|_529 |
i am using the code :
foreach($compare as $value) {
$query = mysql_query("SELECT * FROM `product_info` WHERE `productid`=".$value."");
echo "<table border='1' bordercolor='#000066'>
<tr>
<th>productid</th>
<th>product name</th><br />
<th>price</th>
</tr>";
while ($query_row=mysql_fetch_assoc($query)) {
echo "<tr bgcolor='#F5FFFF'>";
echo "<td>". $query_row['productid']. "</td>";
echo "<td>". $query_row['title']. "</td>";
echo "<td>". $query_row['price']."</td>";
echo "</tr>";
}
echo "</table>";
}
Please give me any suggestion how to compare the price of each product and say like "productA is £_ cheaper than productB" something similar to that would also work.please help.
Move the prices to a new array say product_prices[].
$product_prices['$productID'] = $query_row['price'];
You can then sort this array by increasing/decreasing order of prices and then subtract prices between individual keys.
How you work with the product_prices array is totally left to you and the use case that you have.
UNRELATED - you could get rid of that foreach loop by using mysql's IN clause.
$query = mysql_query("SELECT * FROM `product_info` WHERE `productid` IN (.join(",", $value).")";
SELECT * FROM your_table WHERE price_a <= price_b;
I'm trying to make a database of items for the game "EVE Online" for me and my friends to use, and I set up a SQL server and got tables created and the like, etc etc, and everything's running fine. However, I have one issue when I'm trying to import data from two different tables and compare them against each other within the same html table element. It works perfectly if I just import from one table with multiple columns, but I get issues when I try to select more than one source.
The tables I'm pulling from are...
testmetrics.eve_inv_types
and
testmetrics.items_selling
Ideally, I'd like to import the "name", "type_id", "jita_price_sell" columns from table #1, and "price", "type_id", "station_id", and "qty_avail" from table #2.
I'm also using the ROUND operator on jita_price_sell and price to get a 2 decimal approximation for price points of various items. I also have it so that in table #2 only results with the correct station_id will get displayed. But it keeps throwing up an error!
Here is my code so far...
<?php
$con = mysql_connect("testmetrics.db.10198246.xxxx.com","xxxx","xxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testmetrics", $con);
$result = mysql_query("
SELECT testmetrics.eve_inv_types.name, testmetrics.eve_inv_types.type_id, ROUND(testmetrics.eve_inv_types.jita_price_sell, 2) as jita_price_sell, ROUND(testmetrics.items_selling.price, 2) as price, testmetrics.items_selling.qty_avail, testmetrics.items_selling.sation_id, testmetrics.items_selling.type_id
FROM testmetrics.eve_inv_types, testmetrics.items_selling
WHERE testmetrics.eve_inv_types.type_id = testmetrics.items_selling.type_id, testmetrics.items_selling.station_id = '61000746'");
echo "<table class='sortable'>
<tr>
<th>Item Name</th>
<th>Price (Jita)</th>
<th>Price (K-6K16)</th>
<th>Qty Avail (K-6K16)</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['testmetrics.eve_inv_types.name'] . "</td>";
echo "<td>" . $row['jita_price_sell'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['testmetrics.items_selling.qty_avail'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Any help or insight you could give would be greatly appreciated. I'd also like to be able to do a math function where I'd go something like testmetrics.eve_inv_types.jita_price_sell + (testmetrics.eve_inv_types.volume * 300) to get shipping costs and have that exported to it's own column as well.
Anything you have to say is greatly appreciated!
EDIT: I know I'm already asking for alot of help here, but, does anyone know how to limit returns to "top 100" dependent on the column that it's sorted by? I'm using a Javascript addon to be able to sort easily!
This is the code that solved it for me!
SELECT eve_inv_types.name,
eve_inv_types.type_id,
Round(eve_inv_types.jita_price_sell, 2) AS jita_price_sell,
Round(items_selling.price, 2) AS price,
items_selling.qty_avail,
items_selling.type_id
FROM eve_inv_types
JOIN items_selling
ON eve_inv_types.type_id = items_selling.type_id
AND items_selling.station_id = '61000746'
SELECT eit.name,
eit.type_id,
Round(eit.jita_price_sell, 2) AS jita_price_sell,
Round(eis.price, 2) AS price,
eis.qty_avail,
eis.sation_id,
eis.type_id
FROM eve_inv_types eit
JOIN `items_selling` eis
ON eit.type_id = eis.type_id
AND eis.station_id = '61000746'
You can join tables (assuming you have a key that connects them), here's an example:
table A:
personId
firstName
lastName
numOfChildren
table B:
personId
streetName
cityName
countryName
Select from both (using personID as a join key):
SELECT firstName, lastName, numOfChildren, streetName, cityName, countryName
FROM tableA JOIN tableB USING (personId)
If you want to limit the result you can add:
LIMIT 100
And if you want the top 100 parents you can order by numOfChildren:
ORDER BY numOfChildren
Final Query will look like this:
SELECT firstName, lastName, numOfChildren, streetName, cityName, countryName
FROM tableA JOIN tableB USING (personId)
ORDER BY numOfChildren
LIMIT 100;
-- or --
SELECT firstName, lastName, numOfChildren, streetName, cityName, countryName
FROM tableA JOIN tableB ON (tableA.personId=tableB.personId)
ORDER BY numOfChildren
LIMIT 100;
Read more about join here: http://dev.mysql.com/doc/refman/5.1/en/join.html