Trying to fetch part of the query for a while loop.
I have an INNER JOIN sql query using four tables.
On the first while i'm fetching the orders AKA mod_orders
On the second loop i'm trying to fetch the order products with the information from the other tables AKA mod_orders_pords (pords intended).
so my first while needs to use only SELECT * FROM mod_orders
and the second while needs to loop the rest without the grouping part.
The question is: how do i run the second while?
SELECT * FROM mod_orders AS mo
INNER JOIN mod_orders_pords AS mop
ON mo.`id` = mop.`order_id`
INNER JOIN mod_products_list AS mpl
ON mop.`prod_id` = mpl.`id`
INNER JOIN mod_products AS mp
ON mpl.`id` = mp.`page_id`
GROUP BY mop.`order_id`
ORDER BY mo.`id` DESC
The question is not clear and doesn't specify the issue. I think you need to group all orders with product and product info.
First it is better to avoid * specially if you will access the row using the field name as all tables have id field.
You have order -> orderProduct -> product, so you need to sort by order_id then product id.
Then you will create one while loop and start building your array of objects, see sample code as example.
<?php
//I assume the you have result object using your sql query
$order = new stdClass();
$data = array(); //this array will contains all orders
$order->id = null;
while($row = $result->fetch_assoc()){
if(is_null($order->id) || $order->id != $row['order_id'])
{
//this means that we need to create new order->object
$order = new stdClass();
$order->$row['order_id'];
// add more data like order value etc..
$order->products = array();
$data[] = &$order; //add order by refrence
unset($product);
$product = new stdClass();
$product->id =null;
}
if(is_null($product->id) || $product->id != $row['product_id']){
unset($product);
$product = new stdClass();
$product->id = $row['product_id'];
// add more data like product name etc..
$order->products[] = &$product;
}
}
// unset all objects
unset($order, $product);
using this code you can achieve what you need but remember to sort by order, so first sort by order_id then sort by product_id. order by order_id, product_id. If you have third level added to the order by statement and no need to use group by is this case.
Related
So I have a table ordered_products ordered_products table structure
I have order id and multiple products_id now I want to fetch result based on orders_id and products_id
for example
orders_id =10 , products_ids = array(15,20,21,23)
$result = array();
foreach (products_ids as $value) {
$result=DB::table('ordered_products')->where('orders__id','=',10)->where('products_id','=',$value)->get();
}
I executed the query, but I am only getting single row.
Please help me execute the query.
You should use where for order_id and whereIn for product_ids
$result = DB::table('ordered_products')
->where('orders__id',10)
->whereIn('products_id', $products_ids)
->get();
At the moment, you're running a query for each product, and overwriting $result each time. You can avoid the foreach loop and get all results by using whereIn.
$orders_id =10;
$products_ids = array(15,20,21,23)
$result=DB::table('ordered_products')
->where('orders__id','=',10)
->whereIn('products_id',$products_ids)
->get();
I'm trying to re-write this code so that the drop down menu is alphabetized:
$activeProjectDropdown.="<option value=''>Select Project</option>";
$getInfo = "SELECT id, customer, job_name, haul_info
FROM dispatch_jobs
WHERE (:mydate BETWEEN delivery_date AND delivery_date_end)
ORDER BY customer, job_name";
$result=DB::run($getInfo, ['mydate' => $myDate]);
while($row=$result->fetch(PDO::FETCH_BOTH)) {
if(!empty($row['haul_info'])) {
$haulinfo = "($row[haul_info])";
}else{
$haulinfo = "";
}
if($checkit == $row['id']){
$woot = 'selected=selected';
}else{
$woot = '';
}
$customerName = pdo_getName('name', 'customer', "$row[customer]");
$activeProjectDropdown.="<option value='$row[customer]|$row[id]' $woot>$customerName $haulinfo</option>\n";
}
In this code the query returns some rows from the database where customer is a numeric code which isn't in any kind of alphabetical order. Further down in the code a function called pdo_getName is called which takes a column of name table of customer and the id from $row['customer'] and queries the database, returning the stringified name of the customer. Because the name isn't being retrieved until later on down the loop I'm having trouble figuring out a way that I can alphabetize the $activeProjectDropdown. I've tried putting the $customerName and drop down code into an associative array, then sort that by $customerName and concat everything into a string, but that didn't work because there are duplicate keys. Down that same path, I could potentially have a nested array but I figure there must an easier solution I'm missing. Thanks for the help!
write a JOIN query and get all the data in one query then you can sort on the customers name as I think you are asking to do.
This will improve performance as well as simplify the code.
$getInfo = "SELECT dj.id, dj.customer, dj.job_name, dj.haul_info
c.name
FROM dispatch_jobs dj
LEFT JOIN customer c ON c.id = dj.customer
WHERE (:mydate BETWEEN dj.delivery_date AND dj.delivery_date_end)
ORDER BY c.name, dj.job_name";
$result=DB::run($getInfo, ['mydate' => $myDate]);
while($row=$result->fetch(PDO::FETCH_BOTH)) {
if(!empty($row['haul_info'])) {
$haulinfo = "($row[haul_info])";
}else{
$haulinfo = "";
}
if($checkit == $row['id']){
$woot = 'selected=selected';
}else{
$woot = '';
}
$activeProjectDropdown.="<option value='$row[customer]|$row[id]' $woot>$row[name] $haulinfo</option>\n";
}
Try this:
SELECT ... ORDER BY customer ASC, job_name
This sorts everything by costumer (ascending) first, and then by job_name (ascending, which is the default) whenever the costumer fields for two or more rows are equal.
more info here
I have two tables called mg_product and mg_product_user_property.
In mg_product there are 3 columns: id, title, price as
In mg_product_user_property table product_id corresponds with id column in mg_product table.
So my goal is to get the value of property_id of "15", which in the picture above will be "Mediatek".
This is my SQL:
$sql = "SELECT *
FROM mg_product AS products
INNER JOIN mg_product_user_property AS properties
ON products.id = properties.product_id
WHERE title LIKE '%$search%')";`
PHP:
$resultSet = DB::query($sql);
if ($resultSet->num_rows > 0) {
while ($rows = $resultSet->fetch_assoc()) {
$title = $rows['title'];
$price = $rows['price'];
}
} else {
$output = "No results";
}
Now I need to assign to a php variable the value of property_id=15 so I will be able to print "Mediatek" on my website. How can I achieve that? Sorry for my English.
You are pretty close to what you want, but a couple things are going to either be a mess, or unwanted. So, since there are different ways one can go with this, I will only present a very stripped example (and am INTENTIONALLY leaving out a bunch of code here).
You may not want to do a JOIN like that in the initial search, as for each property, it will also return another of the same product. So looping through that will result in dozens of the same product.
However, if _ALL_YOU_WANT_ is to show the Product Title, Price, and Property 15... you can reduce some headwork with a simpler query:
SELECT p.title, p.price, pr.value
FROM mg_product AS p
LEFT JOIN mg_product_user_property AS pr
ON p.id = pr.product_id AND pr.property_id = 15
WHERE p.title LIKE '%$search%'
The LEFT JOIN means if the property doesn't exist, it will still return the product. But with an empty property value. And this should not return dozens of the same product for every other property in the table.
--
The OTHER way you could go about doing it, using the SQL query you already have (and the dozens of results of the same product it will return), you can alter your php loop like so:
$found_products = array();
while ($row = $resultSet->fetch_assoc()) {
if ($row['property_id'] == 15) {
$found_products[$row['product_id']] = array(
'title' => $row['title'],
'price' => $row['price'],
'prop' => $row['value']
);
}
}
// now you have a clean array of found products that have the property
--
Also I am forced to point out that you should use a prepared statement here, replacing inserting $search directly into the code. But showing you all of how to do that is beyond the scope of this question/answer.
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;
}
I am running a sql query, that pulls the id, catid, name, subof from two tables using inner join.
select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name
Now this results everything i need but I need to loop through the result and do another sql query for the subof value (which is a value, the value being a ID number of the shop_cat). I need to pull the catname of the subof value #, then update the result/array field subof to the name of the cat.
So if the original query gave me a value of 15 for subof, it would do a select catname from shop.cat where id='15' i would take the catname from that query and then update subof = catname for every value in the original result that has a subof value.
EDIT 3/23/13 12:30pm MST: Using more of the code that Opeyemi wrote, to explain more of what I need. I am not sure how else to explain it...
$q = "select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name";
$r = mysql_query();
while(list($shopid, $catid, $name, $catname, $subof) = mysql_fetch_array($r)) {
$getname = mysql_query("select catname from shop_cat where id='$subof'");
$rowname = mysql_fetch_assoc($getname);
//code to update array to change value of $subof to new $rowname['catname']
}
The DB query runs, gets me my values.
I then need to run a loop of some kind, which will loop through every result PHP aquired from the query. This loop will take the subof value (which is a integer ID number) then run a query to get the value catname of that integer value. Then the loop will update the current result and change the subof value from the integer to the catname pulled from the DB in the loop.
I do not need to update the database at anytime, I need to update the result/array from the first query.
What you need to do is to store the resultset in an array and replace within the array.
$q = "select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name";
$r = mysql_query();
$dataset = array();
// Store result in an array
while($assoc = mysql_fetch_assoc($r)) {
$dataset[] = $assoc;
}
// Update array
foreach($dataset as $data) {
$getname = mysql_query("select catname from shop_cat where id='{$data['subof']}'");
$rowname = mysql_fetch_assoc($getname);
// replace data
replace_dataset($data['subof'], $rowname);
}
function replace_dataset($key, $newname) {
global $dataset;
foreach($dataset as $k => $data) {
if ($data['id'] == $key)
$dataset[$k]['subof'] = $newname;
}
}
Are you asking how to do this in PHP or what? If you are looking for how to loop results in PHP it is as simple as this
$q = "select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name";
$r = mysql_query();
while(list($shopid, $catid, $name, $catname, $subof) = mysql_fetch_array($r)) {
// the values from the query are assigned to the variables
// $shopid, $catid, $name, $catname, $subof in that order already
mysql_query("update shop_cat set subof=catname where id='$subof'");
// My interpretation of your query can be wrong though
// But you should get the idea
}
You can use mysql_fetch_assoc() or mysql_fetch_array() or mysql_fetch_row() functions to fetch the row and can put your looping concept on it.
After that you can use mysql_fetch_field() to fetch field subof and id from it.
and update the database after that
You can check the following links
http://www.php.net/manual/en/function.mysql-fetch-array.php
http://www.php.net/manual/en/function.mysql-fetch-assoc.php
http://www.php.net/manual/en/function.mysql-fetch-field.php
I hope you get some idea.