I have 3 tables 1 is an item table, one is a note table and the other is a note image table.
When a user views item details, all notes are picked up for that item (there is a item_id field in the note table)
The notes can have multiple images attached to them these are stored in flat file but are referenced by the "note image" table.
Now when displaying item details I run a query to get all notes for a item... simple enough, then these results are looped through to output them onto the page.
Problem now arises after adding images to notes, how would you go about querying all notes for a item say
SELECT * FROM notes WHERE item = 1
then how would you loop though the result array getting all note images for a note say
SELECT * FROM note_img WHERE note_img_noteid = 27
Its hurting my head a little because I can't visualize how to get the results and output them in PHP.
---EDIT---
Think I may of got it,
SELECT
d.door_note_id,
d.door_note_doorid,
d.door_note_timestamp,
d.door_note_editedtime,
d.door_note_text,
u.user_name AS created_by,
e.user_name AS edited_by,
i.door_img_id AS img_id,
i.door_img_url AS img_url
FROM
user u,
door_note d
LEFT JOIN
user e
ON
user_id = d.door_note_editeduserid
LEFT JOIN
door_img i
ON
door_img_noteid = d.door_note_id
WHERE
d.door_note_doorid = 214
AND
u.user_id = d.door_note_userid
Then I use this:
foreach ($result->result() as $row){
if(!isset($my_items[$row->door_note_id])){ //the note id becaoms a key
//here you set up an array for all the note details
$my_items[$row->door_note_id] = array('door_note_id'=>$row->door_note_id,
'door_note_doorid'=>$row->door_note_doorid,
'door_note_timestamp'=>$row->door_note_timestamp,
'door_note_editedtime'=>$row->door_note_editedtime,
'door_note_text'=>$row->door_note_text,
'created_by'=>$row->created_by,
'edited_by'=>$row->edited_by,
'images'=>array());
}
//if the note has any images add them to the images array for that note.
if(isset($row->img_url)){
$my_items[$row->door_note_id]['images'][] = $row->img_url;
}
}
Its very hard to know when you haven't post your relationships in a table but taking some assumptions
$query = "SELECT items.id as item_id, items.name as item_name, notes.id as note_id,
notes.description as note_description, note_image.image as note_image from notes
LEFT JOIN notes ON items.id = notes.item_id
LEFT JOIN note_image ON notes.id = note_image.note_img_noteid";
//this wil fetch all you items with description, notes and images, because item can have multiple notes, your result wil have multiple entires of the item. so you have to index correctly to use in views
$result = $this->db->query($query)
$my_items = array();
foreach ($result->result() as $row){
if(!isset($my_items[$row->item_id])){ //you item it becaoms a key
//here you set up an array for all your items
$my_items[$row->item_id] = array('item_name'=>$row->item_name, 'notes'=>array());
}
//here you stroe all images fro a note
if(!isset($my_items[$row->item_id]['notes'][$row->note_id])){
$my_items[$row->item_id]['notes'][$row->note_id] = array('note_description'=>$row->note_description, 'images'=>array());
}
$my_items[$row->item_id]['notes'][$row->note_id]['images'][] = $row->note_image;
}
Related
Thanks in advance for any time you spend on my question.
I am trying to display data in a way that will display the manufacturer as a name instead of a number.
Basically when they store the data they choose a manufacturer from a drop down which is generated from a table.. IE Trogues = 1 so products stores the #1 so I know that any beer is associated with trogues is 1. Now I want to display the data but instead of having a 1 I would like to have Trogues be displayed. Where you see manufacturer in the echo code below..
I am not understanding the process logic here..
error_reporting(E_ALL);
ini_set('display_errors', 1);
$sql = "SELECT * FROM products
LEFT JOIN manufacturer
ON product.manufacturer = manufacturer.id
ORDER BY manufacturer.id, product.id";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
echo "
<div class=reportclientproduct>".$row['manufacturer']." - <a href=".$row['website']." target=_blank>".$row['product']."</a></div>";
}
Have you tried the query like this:
$sql = "SELECT man.id AS manufac, products.product AS prod FROM products
LEFT JOIN manufacturer as man
ON product.manufacturer = manufacturer.id
ORDER BY manufacturer.id, product.id";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
echo "
".$row['manufac']." - ".$row['prod']."
";
}
Assuming that the table products had a column named manufacturer which holds the ID of the manufacturer, and that both tables have columns name ID which hold the ID of the table item.
Also the JOIN functions may vary based on the database you use. But the aforementioned method is for mysql.
I have category table which stores all category info [parent and child both] , category_child table which stores parent and child category relation, and product_category table which stores relation between child_category and product.
category - All Category {cid, cname, isParent, status} column.
category_child - Realtion {parent_id, child_id}.
category_product - Relation {product_id, child_category_id}
product - All product details {pid, pname, pimage, pprice,pstock}
I am displaying all Parent Category Link in Front page. Now, Whenever any person will click on parent category Link, I want to display 4 product information from each child category of parent category.
here is my code, which is horrible at the moment, and i am looking for some help in minimising it as much as possible.
$fetchChild = $mysqli->query("SELECT child_id from category_child where parent_id='".$mysqli->real_escape_string($pid)."'");
$listchild = array();
if($fetchChild->num_rows > 0) {
$n = 1;
while($storeChild = $fetchChild->fetch_assoc()) {
$listchild['child_id'][$n] = $mysqli->query("SELECT product_id from category_product where child_category_id='".$mysqli->real_escape_string($storeChild[$n])."'");
if($listchild['child_id'][$n]->num_rows > 0) {
$i = 1;
while($storeMore = $listchild['child_id'][$n]->fetch_assoc()) {
$listchild['product_id'][$i] = $mysqli->query("SELECT pid, pname, pimage, pprice, pstock from product where pid='".$mysqli->real_escape_string($storeMore[$i])."'");
if($listchild['child_id'][$n]['product_id'][$i]->num_rows > 0) {
$me = 1;
while($smeLast = $storeMore[$i]->fetch_assoc()) {
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pid'];
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pname'];
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pimage'];
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pprice'];
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pstock'];
$me++;
}
} else {
echo '<meta http-equiv="refresh" content="0; url=index.php?error=Something+Went+Wrong+We+are+Fixing+it" />';
}
$listchild['product_id'][$i]->free();
$i++;
}
}
$listchild['child_id'][$n]->free();
$n++;
}
} else {
echo '<meta http-equiv="refresh" content="0; url=index.php" />';
}
$fetchChild->free();
Kindly help in minimizing nested while and query in my code.
Thanks
If you want, you can put everything into one SQL query using JOIN statement.
SELECT `category`.*, `product`.* FROM `product`
LEFT JOIN `category_product` ON `category_product`.`product_id` = `product`.`pid`
LEFT JOIN `category_child` ON `category_child`.`child_id` = `category_product`.`child_id`
LEFT JOIN `category` ON `category`.`cid` = `category_child`.`child_id`
WHERE `category_child`.`parent_id`='".$mysqli->real_escape_string($pid)."'
But I don't think it's the best solution.
PS. By the way, there is no LIMIT of 4 products per child category in your code, so I haven't put it either.
You can reduce all your queries to one query with JOINS. Using joins will allow you to return results from one table (e.g. product) basing on the conditions provided in another table or tables (e.g. category_product, category_child).
Read more about joins somewhere at Stack Overflow or browse some other resources. For example http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html .
You should never use SQL query in a loop! It is very slow, you can overload the sql server etc...
Your database structure is bad. If you want to store hiearchical tree there are better options:
Tree 1 level:
1A2
Tree 2 level:
1A6
2B3 4C5
Tree 3 level:
1A12
2B7 8C9 10D11
3E4 5F6
You have a left and a right value by each node, and you can have the parent id too. You can check whether a node is leaf or branch if you check the difference of the right-left. By leaves it is one. You can check whether a leaf is under a branch if its left is bigger than the left of the branch and its right is smaller than the right of the branch. etc... This structure is described on several sites, for example here: nested set model
After you transformed your model to nested set, you can use a simple sql to ask for your products. Something like this:
SELECT
p.*
FROM
categories c, categories b, products p, product_categories pc
WHERE
b.category_id = ?
AND
c_category_id <> b.category_id
AND
c.category_left BETWEEN b.category_left AND b.category_right
AND
c.category_right - c.category_left = 1
AND
c.category_id = pc.category_id
AND
p.product_id = pc.product_id
This is good for beginning, your code will contain group by, limit, etc... because you want to ask only a single product per category... (or you can simply use order by rand() and limit 4 ...)
You should use prepared statements instead of manual escaping... http://php.net/manual/en/mysqli.prepare.php
I'm loading comments for product with id = '3'
$get_comments = mysql_query("SELECT * FROM products_comments WHERE product_id = '3'");
Now I want to add the "report abuse" option for each comment, for this purpose I'm having another table as "abuse_reports" which user abuse reports will be stored in this table, now if a user reported a comment, the report abuse option should not be there for that comment for that user there anymore, for this I'm doing:
while($row = mysql_fetch_array($get_comments)){
echo blah blah blah // comment details
// now for checking if this user should be able to report this or not, i make this query again:
$check_report_status = mysql_query("SELECT COUNT(id) FROM abuse_reports WHERE reporter_user_id = '$this_user_id' AND product_id = 'this_product_id'");
// blah blah count the abuse reports which the current user made for this product
if($count == 0) echo "<a>report abuse</a>";
}
With the above code, for each comment I'm making a new query, and that's obviously wrong, how I should join the second query with the first one?
Thanks
Updated query (that is working now, commited by questioner)
SELECT pc. * , count( ar.`id` ) AS `abuse_count`
FROM `products_comments` pc
LEFT OUTER JOIN `abuse_reports` ar ON pc.`id` = ar.`section_details`
AND ar.`reporter_id` = '$user_id'
WHERE pc.`product_id` = '$product_id'
GROUP BY pc.`id`
LIMIT 0 , 30
The query works as follow: You select all the fields of your products_comments with the given product_id but you also count the entries of abuse_reports for the given product_id. Now you LEFT JOIN the abuse_reports, which means that you access that table and hang it on to the left (your products_comments table). The OUTER allows that there is no need for a value in the abuse_reports table, so if there is no report you get null, and therefore a count of 0.
Please read this:
However, I needed to group the results, otherwise you get only one merged row as result. So please extend your products_comments with a field comment_id of type int that is the primary key and has auto_increment.
UPDATE: abuse count
Now you can do two things: By looping through the results, you can see for each single element if it has been reported by that user or not (that way you can hide abuse report links for example). If you want the overall number of reports, you just increase a counter variable which you declare outside the loop. Like this:
$abuse_counter = 0;
while($row = mysql....)
{
$abuse_counter += intval($row['abuse_count']); // this is 1 or 0
// do whatever else with that result row
}
echo 'The amount of reports: '.$abuse_counter;
Just a primitive sample
I believe your looking for a query something like this.
SELECT pc.*, COUNT(ar.*)
FROM products_comments AS pc
LEFT JOIN abuse_reports AS ar ON reporter_user_id = pc.user_id AND ar.product_id = pc.product_id
WHERE product_id = '3'"
try this SQL
SELECT pc.*, COUNT(ar.id) AS abuse_count
FROM products_comments pc
LEFT JOIN abuse_reports ar ON pc.product_id = ar.product_id
WHERE pc.product_id = '3' AND ar.reporter_user_id = '$this_user_id'
GROUP BY pc.product_id
The result is list of products_comments with abuse_reports count if exist for reporter_user_id
Hi and thanks in advance for your answer/s.
I have two tables, tracks(info on music tracks, title, lenght, cd_id..etc) and purchd_items(purchased tracks, cd_id, user_id..etc). I have this query:
function blue($id)
{
$user_id = $this->tank_auth->get_user_id();
$query = $this->db->query("SELECT tracks.id, tracks.track_id, tracks.cd_id, tracks.title, tracks.lenght, tracks.price, tracks.file, tracks.preview, tracks.hash, purchd_items.cd_id, purchd_items.name FROM tracks LEFT JOIN purchd_items ON tracks.cd_id = purchd_items.cd_id WHERE purchd_items.user_id = $user_id AND tracks.cd_id = $id GROUP BY tracks.title, purchd_items.name ORDER BY tracks.track_id");
return $query->result();
}
What I am trying to do check two tables for match and display all the info from tracks table as well as matching items from purchd_items table that will replace the entries from tracks table. If the user has already bought any tracks I want to display the download link instead of usual buy track link.Kind of like itunes, I guess.
I was sort of able to get this working using the query above but the number of items in the returned array was multiplied by the number of entries in the purchd_items table and I couldn't get rid of the duplicates.
Hope I am making sense here! Thank you!
I figured it out!
SELECT tracks.id, tracks.track_id, tracks.cd_id, tracks.title, tracks.lenght, tracks.price, tracks.file, tracks.preview, tracks.hash, purchd_items.cd_id, purchd_items.name FROM tracks LEFT JOIN purchd_items ON tracks.cd_id = purchd_items.cd_id AND purchd_items.name = tracks.title AND purchd_items.user_id = $user_id WHERE tracks.cd_id = $id ORDER BY tracks.id
I am looking for a cleaner way to do this. My code works, but I know it can be better. I have three tables: one with a list of Category Groups, One with a list of categories that are linked to category groups, and one with a list of news stories that are linked to the categories.
I need to loop through all of the names of the Category Groups, followed by the names of the categories that are in the category groups, with the number of news stories in each category listed as well.
I have three tables: CategoryGroups, Categories, News.
I have a set of queries. The first queries all the rows from the CategoryGroups table:
$result = mysql_query( '
SELECT cat_group_id, cat_group_name FROM CategoryGroups
' );
The second query is inside the looped results of the first query and finds all the categories that have a news item and are linked to a specific category group:
<?php
while( $row = mysql_fetch_assoc( $result ) ){
$id = $row['cat_group_id'];
$name = $row['cat_group_name'];
echo "<h3>$name</h3>";
$sql = mysql_query("
SELECT category_id, title FROM `Categories`
WHERE cat_group_id = $id
AND category_id IN
(SELECT news.category_id FROM news)
");
while( $row = mysql_fetch_assoc($sql) ) {
$title = $row['title'];
$catid = $row['category_id'];
$numbers = mysql_query("
SELECT * FROM news
WHERE category_id =$catid"
);
$nums = mysql_num_rows($numbers);
echo "$title ($nums)<br/>\n";
}
?>
I would like to limit this to one or two queries, with efficiency in mind. I know this can be done, however I have not been successful in my attempts.
thanks.
Why not JOIN the tables?
SELECT cat_group_name, title, count(newsid)
FROM CatagoryGroups
INNER JOIN Categories ON cat_group_id
INNER JOIN News ON category_id
GROUP BY cat_group_name, title
looks like it should be close, if table news has a newsid column (it's gotta have SOME primary key, right? well, count that;-). With the obvious indexes the JOINs should be quite fast, and your PHP code can do whatever output formatting you may need from that.
I suggest you need to get a book on SQL, such as "SQL Queries for Mere Mortals."
$sql = mysql_query("
SELECT cg.cat_group_name, c.title, COUNT(n.category_id) AS NumNews
FROM `CategoryGroups` cg
JOIN `Categories` c USING (cat_group_id)
JOIN `News` n USING (category_id)
GROUP BY cg.cat_group_name, c.title");
Then loop over the result and output a new <h3> each time the cat_group_name is different from the previous row.