PHP - Query inside query - php

I have a very simple query but I need to make another query inside it. I have very little knowledge of SQL and PHP so I want to ask your help.
$result = mysql_query("SELECT * FROM img");
while ($row = mysql_fetch_assoc($result))
{
$imgName = $row['name'];
$catID = $row['catid'];
// Problem
// Need to get category NAME from category ID
$result2 = mysql_query("SELECT name FROM cat WHERE id = $catID");
while ($row2 = mysql_fetch_assoc($result2))
{
$catName = $row2['name'];
}
echo "Image: $imgName <br />";
echo "Category: $catName";
}

This looks to be a simple JOIN to get the category name. You can use a single query:
SELECT
img.id AS imgId,
img.name AS imgName,
cat.name AS catName
FROM img JOIN cat ON img.catid = cat.id
Replace your initial query with the above, and it will eliminate the need for the inner query.

You could do a simple subquery on this one:
$result = mysql_query("
SELECT name, catid, (SELECT name FROM cat WHERE id = img.catid) AS cat_name
FROM img
");

This should work. You'll see all the img properties of each table in each row and in addition the cat.name value.
SELECT *, cat.name as catname FROM img
INNER JOIN cat
ON cat.id = img.catid

Related

Putting data from two different loops in a google pie chart

So I have this code for my Google pie chart (pie chart code not included, but it works fine and displays data)
<?php
$query = "SELECT * FROM category WHERE type = 'Expense' ";
$select_category_list = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_category_list)) {
$cat_id = $row['id'];
$cat_title = $row['title'];
echo "['$cat_title'" . ",";
echo "$cat_id],";
}
?>
I put the echo in different lines, but it really does not matter to if they are in one line or in two lines, what matters is to get it finally working :)
Instead of $cat_id I want to put the SUM ($cat_amount) calculated by this code:
$query = "SELECT category_id, SUM(amount) AS TotalAmount FROM spendee
WHERE type = 'Expense' group by category_id ";
$expense_query = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($expense_query)) {
$cat_amount = $row['TotalAmount'];
}
I have tried putting while loop in a while loop, foreach loop in a while loop, putting $cat_amount instead of $cat_id (that only displays one SUM) and so on. Nothing worked. I have not tried the for loop, but I assume the result would be the same + I am not sure how would I define the times that the loop needs to run, since there could be many type 'Expense' categories added in time.
Any help would be very much appreciated. Thank you and have a lovely day.
maybe i'm missing something, but looks like you could join the two tables in one query
this would get the desired result in one query / loop...
sql:
SELECT a.title as Title, SUM(b.amount) AS TotalAmount FROM category a, spendee b WHERE b.category_id = a.id and b.type = 'Expense' group by a.title
php:
<?php
$query = "SELECT a.title as Title, SUM(b.amount) AS TotalAmount FROM category a, spendee b WHERE b.category_id = a.id and b.type = 'Expense' group by a.title";
$select_category_list = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($select_category_list)) {
$cat_title = $row['Title'];
$cat_amount = $row['TotalAmount'];
echo "['$cat_title'" . ",";
echo "$cat_amount],";
}
?>

trying to form SQL join on several tables

So Im trying to figure out how to do this with 1 query if possible. Here is what I have with several queries
$file_url = 'http://'.$cms.'/filemanager/gallery';
$link_url = '/our-process/gallery/';
include 'inc/config.php';
function gallerySafeName($var){
$var = strtolower(preg_replace('([^a-zA-Z0-9_])','-',$var));
return $var;
}
$galleryimages = array();
$sql = "SELECT * FROM `cms_gallery_categories` ORDER BY RAND() LIMIT 3";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)){
$sql1 = "SELECT * FROM `cms_gallery_images` WHERE `image_id` = ".$row['category_image_id'];
$result1 = mysqli_query($con,$sql1);
while ($row1 = mysqli_fetch_array($result1)){
$sql2 = "SELECT * FROM `cms_gallery` WHERE `gallery_id` = ".$row1['gallery_id'];
$result2 = mysqli_query($con,$sql2);
while ($row2 = mysqli_fetch_array($result2)){
print '<li>
<a href="'.$link_url.$row['category_name'].'/'.$row2['gallery_name'].'/'.gallerySafeName($row1['image_caption']).'/">
<img width="210" height="133" border="0" src="'.$file_url.'/'.$row['category_name'].'/'.$row2['gallery_name'].'/'.$row1['image_name'].'" />
</a>
</li>';
}
}
}
Im trying to get 3 random entries from the gallery category and the image assigned to represent that category. Then get the gallery name and then the image name to form a img src and link. My table structure is as follows
-cms_gallery_categories
category_id
category_title
category_name
category_image_id
-cms_gallery
gallery_id
gallery_title
gallery_name
category_id
-cms_gallery_images
image_id
image_name
image_caption
gallery_id
Images belong to galleries, and galleries belong to categories
SELECT GC.*, G.*, I.*
FROM cms_gallery_categories GC
INNER JOIN cms_galleries G ON (G.category_id = GC.category_id)
INNER JOIN cms_gallery_images I ON (I.gallery_id = G.gallery_id)
ORDER BY RAND() LIMIT 3
You will want to limit your fields to what you need only. From what I can see in your code, it's this:
SELECT GC.category_name, G.gallery_name, I.image_caption FROM...
More info
http://www.w3schools.com/sql/sql_join.asp
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
http://www.tutorialspoint.com/sql/sql-using-joins.htm

How to Get another value in another table using a dynamic call

I currently have this query with an array that outputs the variables within using a dynamic input in my form (term), this creates a Dynamic Search with auto complete to fill in all of the details for a product.
$return_arr = array();
$param = $_GET["term"];
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
//$row_array['category_id'] = $row ['category_id'];
$row_array['product_id'] = $row['product_id'];
$row_array['product_names'] = $row['name_en-GB'];
$row_array['jshop_code_prod'] = $row['product_ean'];
$row_array['_ext_price_html'] = number_format($row['product_price'],2);
if (!empty($row['product_thumb_image']) AND isset($row['product_thumb_image'])){
$row_array['image'] = $row['product_thumb_image'];
}else {
$row_array['image'] = 'noimage.gif';
}
array_push( $return_arr, $row_array);
}
mysql_close($conn);
echo json_encode($return_arr);
Unfortunately I also need to get the category_id which is not in the same table, I have tried to modify my query as such, but to no avail:
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param' AND `crd_jshopping_products_to_categories` = `product_id` ");
What step am I missing here ? The product_id's match in both tables?
try this query instead and try to understand what I have written in it:
$fetch = mysql_query("
SELECT
p.*,
c.category_id
FROM
crd_jshopping_products as p
INNER JOIN crd_jshopping_products_to_categories as c
ON p.product_id = c.product_id
WHERE
`p.name_en-GB` REGEXP '^$param'
");
This means:
SELECT:
Give me everything from p and the category_id from c.
FROM:
Do this from rows in the tables crd_jshopping_products (referred to as p) and crd_jshopping_products_to_categories (referred to as c), where the rows match on the count of p.product_id is the same as c.product_id.
WHERE:
Only return the rows where p.name_en-GB REGEXP '^$param'.

List products under each category heading in a single page

I have two tables
First one is categories and second one is products.
Categories table contains cat_id, cat_name, Cat_desc.
Products table contains product_id, product_name, Product_desc and cat_id
I want to display all categories as heading and list only 4 related products under each category heading.
For Eg:
Category1
Product 1, Product 2, product 3
Category 2
Product 4, product 5
How can I script this. I am newbie pls help
OK i think this is ok with your question. try this...
$sql = "SELECT cat_id, cat_name FROM categories ";
$query = mysql_query($sql);
while($result = mysql_fetch_array($query)){
echo $result['cat_name'];
$sql1 = "SELECT * FROM products WHERE cat_id=".$result['cat_id'];
$query1 = mysql_query($sql1);
while($row = mysql_fetch_array($query1)){
echo $row['product_name'];
}
}
AND refer this http://php.net/manual/en/book.mysql.php
With the help of Nytram's post, I just alter the code. So this answer is 99% owes to Nytram.
$sql = "SELECT cat_id, cat_name FROM categories ";
$query = mysql_query($sql);
while($result = mysql_fetch_array($query)){
echo $result['cat_name'];
And altered line is:
$sql1 = "SELECT * FROM products WHERE cat_id='".$result['cat_id']."' LIMIT 0,10";
Then use the same code
$query1 = mysql_query($sql1);
while($row = mysql_fetch_array($query1)){
echo $row['product_name'];
}
}
Try this ::
Select * from
categories c left join products p on (p.catId = c.catId)
order by c.catId
You can refer to this tutorial
You need to do a recursive function for this
i call this category tree
http://codeassembly.com/How-to-display-inifinit-depth-expandable-categories-using-php-and-javascript/

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

Categories