Combine sub query with multiple results into one - php

How can I achieve the following using only one database query?
$query = "SELECT `email`, `name` FROM `customers`";
$result = mysqli_query($link,$customer_query);
while($row = mysqli_fetch_array($result)){
echo "<p>".$row['name']."</p>";
echo "<ul>";
$query2 = "SELECT `sku` FROM `orders` WHERE `email` = '".$row['email']."'";
$result2 = mysqli_query($link,$query2);
while($row2 = mysqli_fetch_array($result2)){
echo "<li>".$row2['sku']."</li>";
echo "<li>".$row2['cost']."</li>";
}
echo "</ul>"
}

Use INNER JOIN on email field for this:
SELECT c.name, o.sku, o.cost FROM customers c INNER JOIN orders o ON o.email = c.email
Don't forget to add MySQL INDEX on email field for performance.
But this only select customers which have orders.
If you need to select all customers (even which does not have orders) use LEFT JOIN instead. In this case sku and cost fields for users without orders will be null.
Use this picture as hint for this.

Related

1 JSON object, 2 queries, 2 tables

Here is my simple query:
$sql = "SELECT * FROM donations Order By userid";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()){
$json[] = $row;
}
$data['data'] = $json;
I use it to display all data from the 'donations' in a table. Fields are: userid,date,amount.
In that same table, I'd like to add firstname and lastname of corresponding userid which are stored in mymembers table. The condition should be WHERE donations.userid = mymembers.id.
I need help adding that condition for every row resulting from the $sql query.
Use join and change query to
SELECT * FROM donations
INNER JOIN mymembers on (donations.userid = mymembers.id)
Order By donations.userid

Get data from two different tables in the same query

I'm starting to learn php. I'm able to extract the list of CD from the SQL query in [in this table][1] but there's another query which contains the Category which is linked via ID in this table.
How do I get all the columns in the same result set using one query?
<?php
include 'database_conn.php';
$sql = "SELECT id, title, year, price FROM table_cd";
$queryresult = mysqli_query($conn, $sql)
or die (mysqli_error($conn));
while($row = mysqli_fetch_assoc($queryresult)) {
$iid = $row['id'];
$title = $row['title'];
$year = $row['year'];
$price = $row['price'];
echo "<div>
$title
</div>\n";
echo $row['year'];
echo $row['price'];
}
?>
editCDForm.php:
<?php
$code = $_GET['itemCode'];
$sql = "SELECT * FROM table_cd WHERE table_category.ID = $code
JOIN table_category ON (table_category.Desc = table_cd.ID)";
?>
What you're looking for is called a JOIN which allows you to merge the rows from two or more tables into the same result set.
You can modify your query as illustrated below, by using a LEFT JOIN of the nmc_cd table and the nmc_category table on the catID column, as the common primary attribute between them, giving you the desired result set...
$sql = "SELECT nmc_cd.CDID, nmc_cd.CDTitle, nmc_cd.CDYear,
nmc_cd.CDPrice, nmc_category.catDesc
FROM nmc_cd
JOIN nmc_category on nmc_cd.catID = nmc_cd.catID";
Here's a nice article that may help you visualize what a JOIN looks like in your SQL.
Syntax for joins:
SELECT * FROM table1
JOIN table2 ON (table2.colunmname = table1.columnname)
use can get the data from both tables when joining them:
$sql = "SELECT FT.CDID, FT.CDTitle, FT.CDYear, FT.CDPrice,
ST.catDesc FROM nmc_cd AS FT LEFT JOIN nmc_category as ST ON
FT.catID=ST.catID";

How can i remove duplicate values from an Echoed table?

I have managed to create a JOIN query for three tables and can successfully echo out the results in a echoed table, here is my code:
<?php
$sql="SELECT a.product_id, a.Options_id, b.product_name, b.product_price, c.Options_name, c.Price_diff
FROM ProductOptions a
JOIN Products b ON a.product_id = b.product_id
JOIN Options c ON a.Options_id = c.Options_id
ORDER BY product_name DESC";
$result = mysql_query($sql);
if (!$result)
{
echo "An error occurred ".mysql_error();
exit;
}
echo "<table border=1>\n<tr><th></th><th bgcolor=\"#DFE8EC\">Name</th><th>Flavors & Size</th><th bgcolor=\"#DFE8EC\">Price</th><th>Price Difference</th><th bgcolor=\"#DFE8EC\"></th></tr>\n";
while ($line = mysql_fetch_array($result)) {
$name = $line["product_name"];
$price = $line["product_price"];
$options=$line["Options_name"];
$difference=$line["Price_diff"];
echo "<tr><td></td><td bgcolor=\"#DFE8EC\">$name</td><td>$options</td> <td bgcolor=\"#DFE8EC\">£$price</td><td>£$difference</td><td bgcolor=\"#DFE8EC\"></td></tr>\n";
}
echo "</table>\n";
?>
My table works but it shows duplicate entries for product_name and I do not know how to remove them.
You have to use a GROUP BY clause in your query like this:
$sql = "SELECT a.product_id, a.Options_id, b.product_name, b.product_price, c.Options_name, c.Price_diff
FROM ProductOptions a
JOIN Products b ON a.product_id = b.product_id
JOIN Options c ON a.Options_id = c.Options_id
GROUP BY product_name
ORDER BY product_name DESC";

Counting Number Of Classifieds In Category

I have a table categories that has: id, name, subcategory_id, parent_id. Another table classifieds that has: classified_id, title, description, category_id.
I am trying to to pull numbers of classifieds in each category. So it will look like this.
Accessories(10)
Cars(15)
Dating(12)
I gave it a try like this:
enter $catquery = mysql_query("SELECT * FROM categories WHERE sub_id = '0' ORDER BY name ASC"); here
enter $catrows = mysql_num_rows($catquery); here
enter $catrows = mysql_num_rows($catquery); here
enter $query = "SELECT category_id, COUNT(title) AS `total` FROM classifieds WHERE classified_id = 'category_id' "; here
enter $result = mysql_query($query); here
enter while($row = mysql_fetch_assoc($result)){ $num_items_in_category[$row['category_id']] = $row['total']; here
enter } echo "<li><a href='category.php?cat=".$row['id']."'>".$row['name']. $row['total']. "</a></li>"; here
Thanks fellas
You should be able to accomplish what you're looking for by joining the 2 tables.
SELECT a.name, count(*) as cnt
FROM categories a
join classifieds b
on a.id = b.category_id
group by a.name
COUNT is an aggregate function, so you can get all of the counts at once.
I believe what you are looking for is
$query = "SELECT category-id, COUNT(title) AS `total` FROM classifieds WHERE classified-id = 'category-cat' GROUP BY category-id";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$num_items_in_category[$row['category-id']] = $row['total'];
}
This will give you associative array with the count of records for each category-id

select row where the slot is the biggest

i need to select one row where slot_left is the biggest. i tried
for ( $i=1;$i<3;$i++) {
$sql5 = "SELECT * from user u where (
select max(slot_left) from company c,user u
where c.id=u.company_id and c.id='$name'
)";
$result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
while($row=mysqli_fetch_array($result5)) {
// echo the id which the slot_left is the biggest
echo $i['slot_left'];
}
}
but still cannot. please help!
You have to use GROUP BY in your query.
And query execution in Loop is not recommended, it will decrees performance.
Try this.
$sql5 = "select c.id, max(slot_left) from company c,user u
where c.id=u.company_id and c.id='$id' GROUP by c.id";
$result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
while($row=mysqli_fetch_array($result5)) {
echo $row['slot_left'];
}
SQL can be. You select all rows from DB.
$sql5 = "select max(slot_left) AS slot_left from company c,user u where c.id=u.company_id and c.id='$name' GROUP by u.company_id";
$name variable used in query not set
Variable $i is not array. Array is $row
echo $row['slot_left'];

Categories