Get multiple results from db - php

I'm working on a fairly large project in (object oriented) PHP which includes a webshop where users can buy products and additional licenses and services. Purchasing is a four step process:
Step 1: User chooses a product, and product_id is passed to step 2
Step 2: Fetching and outputting all license types based on product_id, passing product_id on to step 3
Step 3: Fetching and outputting all services based on product_id, in a form with checkboxes named services[$service_id]
So now, on the checkout on step 4, I fetch the correct products and licenses from the database, but I also have to get the correct services from the db based on the services array, and calculate the price to output. At last, I'll have to assign the services array to the Smarty template.
How would the most suitable way to do this be? I really hope that someone is kind enough to help me out here, as I'm having a very hard time trying to make this work.
Thank you so much in advance.

Try using
$resulter = array();
$i = 0;
foreach($product_id as $value) {
$query = "Select FROM products WHERE product_id = $value";
Your execution code
$resulter[$i] = $result; //$result could be a assoc array
$i++
}
And If I ware you I would i would use a multidimensional array like I shown above.

Sounds like you need a JOIN.
Something like a JOIN on the 'products' table and 'licences' table using the 'product_id' field to make the join.
An example query would be something like:
SELECT <required_fields_here>
FROM products
JOIN licences ON licences.product_id = products.product_id
WHERE product_id = <product_id_here>
Note that in the SELECT section you can select fields from both 'products' and 'licences' tables, you just need to prefix with the table and a dot e.g. 'product.product_id'
I think you will need to be more specific if you need further help. Hope it helps.

Related

Joining Multiple Tables using CodeIgniter

I'm needing some help with pulling data from multiple tables ( 3 total ). I know there is the JOIN option, but I'm still having some trouble. Not sure if I can JOIN the tables in one query to get my results. I'll try to explain what I'm doing before I post my attempted code...
I'm trying to make an "Inventory Need" section on my site. I've got an INVENTORY_PRODUCTS table where I check to see if the column UNITSINSTOCK is less than the MINLEVEL qty. Pretty simple. But I also need to check and see if that product is "On Order". To do that I need to check my INVENTORY_ORDERS AND INVENTORY_ORDER_DETAILS tables.
The status of the order is in the INVENTORY_ORDERS table ( if it's 1 or NULL ) and then the details for the orders are in INVENTORY_ORDER_DETAILS. So I will need the SUM for that item if it exists.
My HTML table has the following columns: Product #, Min, Max, Stock, On Order and Need.
This is what I'm trying to use:
function get_inventory_below_need($mfctId) {
$this->db->select('
INVENTORY_PRODUCTS.ID, INVENTORY_PRODUCTS.PRODUCTNUMBER, INVENTORY_PRODUCTS.MINLEVEL, INVENTORY_PRODUCTS.MAXLEVEL, INVENTORY_PRODUCTS.UNITSINSTOCK,
SUM(INVENTORY_ORDER_DETAILS.QUANTITY) AS ORDERQTY
');
$this->db->from('INVENTORY_PRODUCTS');
$this->db->join('INVENTORY_ORDER_DETAILS', 'INVENTORY_ORDER_DETAILS.PRODUCTID = INVENTORY_PRODUCTS.ID', 'INNER');
$this->db->join('INVENTORY_ORDERS', 'INVENTORY_ORDERs.ID = INVENTORY_ORDER_DETAILS.ORDERID', 'LEFT');
$this->db->where('INVENTORY_PRODUCTS.MANUFACTURERID', $mfctId);
$this->db->where('INVENTORY_ORDERS.STATUS != 9');
$this->db->where('INVENTORY_PRODUCTS.UNITSINSTOCK < INVENTORY_PRODUCTS.MINLEVEL');
$this->db->group_by('INVENTORY_PRODUCTS.PRODUCTNUMBER');
$this->db->order_by("INVENTORY_PRODUCTS.PRODUCTNUMBER", "asc");
$query = $this->db->get();
return $query->result();
}
The problem is it's only displaying items that have a stock level below the min level AND are currently being ordered. But I've got some products that are below min level and not being ordered.
Hope all this makes sense!
$query = $this->db->query('enter sql query here');
sure you will have to type out the query that you want to use, but it will most likely look nicer and if you are using PHP MyAdmin or have another way to access the database you can test it.

Related products algorithm

When inserting products in an eshop we often need to link some products (aka related products) to others and the linking must be done both ways, meaning if I link product1 to product2 then product2 must also be linked to product1.
Which is the best practice, using an extra table 'relations' (prodid, related_prodid) or to keep a list of related products in a delimited string in each product's row in the products table?
In either case, we would also need a recursive method to loop through a given array of products and insert/update the tables with the relations, could someone help me out with the algorithm? I will do the PHP coding but I cant think of a good way to do it.
You'd better use an intermediate table related_to(id, product1, product2)
Then, you'll use the code:
function findRelatedProducts($product) {
$relatedProducts = array();
$data = mysql_query("SELECT * FROM related_to WHERE product1='$product' OR product2='$product'");
while ($relation = mysql_fetch_array($data)) {
$relatedProducts[] = $relation['product1'] == $product ? $relation['product2'] : $relation['product1'];
}
return $relatedProducts;
}
Of course, you need to JOIN this table with your product table, but since I don't have much informations about your mysql structure, I'll let you check on this site if you don't know how.
Definitely use the extra table (the string solution is really a bad idea), preferably organizing it so that the product with the lowest primary key is put first in the relation (allows for a bit of optimization); there is no need to duplicate the relationships (i.e. having and at the same time).
As for the recursive method thing, it's not clear where you get the relations' value from.

Combining multiple rows or results with the same title to form drop down menus with PHP and MySQL

So I am picking up a project that was quit halfway through by the last guy so that I could get some more practice with PHP and databases. I have run into a problem, and I am sure it is common enough that there is a standard solution, but I am unable to find one.
The db I am working with has 4,600, so reorganizing is out of the question. It is a db of liquers for a wholesaler. Here is what the results page looks like currently:
What I am trying to set it up so the results are returned in list form, with only one title and dropdown menus for the different sizes/prices of products that looks like this:
The problem is that there are multiple entries in the db for each product. In this example there are 3, while some have 1, and some have 2.
I am really not sure how to go about this, and any help would be greatly appreciated. Thank you.
I'm not sure about the PHP syntax, but pseudocode here's what you could do:
allProductsReturnedFromMySQL = QueryYourDatabaseForAllProducts()
Hashtable[productId, List[productSizes]] dropDownsByProduct;
Hashtable[productId, commonProductInformation] uniqueProducts;
foreach (product in allProductsReturnedFromMySQL) {
if product.productId not in uniqueProducts
then add it with the product information that does not vary
if product.productId not in dropDownsByProduct
then add it with an empty list
append the size of this product to the corresponding list in dropDownsByProduct
}
After that little bit of logic you'll have all your unique products with the common properties for each one, and a way to fetch the corresponding sizes drop down. If you wanted to do this purely in SQL to minimize the data that's transferred, you could do something like this:
-- this would get you your products
select distinct id, property1, property2 from product
-- this would get you your drop downs by product
select id, size from product order by id
You can then build the same drop down hashtable by iterating through the second result set.
I'm not sure if this is the best way, but I've always approached this by altering the query so that it is sorted by product name. Then as you iterate through the rows, check to see if the product name matches the one you just processed. If it's the same, then this row is a different size of the same project.

Tricky MySQL Insert and Update

I'm making a shopping cart for my website.
When an user add something into the cart it should insert item_id and quantity into the items column in my DB.
The item column should hold a string like this:
1:5;6:2;13:1
item_id:quantity;item_id:quantity and so on
The insert part I already got, but when the user wants to view the cart, the string needs to be split into an array and fetch the items from another table
Array example:
1 => 5,
6 => 2,
13 = 1
I'v tried using spliti(";" $raw);
But didn't get what I wanted.
And the same thing when the user updates/deletes a product from the cart..
When the user updates/deletes a product, it must search through the string inside items and find the current place of the product.
Any help would be appreciated :)
Since you are building your own cart do it correctly using a properly normalized schema. This means that you need to avoid "special" values which do more than 1 thing at the same time.
So the obvious improvement here is to have:
table users:
id
...
table products:
id
...
table cart_items:
user_id
product_id
quantity
CRUD queries will be very simple to implement then and also very fast.
First off, I don't think it's a good idea to have your items as a string in your order/cart table. You run into a lot of problems this way (you've already run into a couple).
It's better to have a hasMany relationship. Something along the likes of the design shown below is ideal.
Order Table : id, date, total, more, fields
OrderItem Table : id, order_id, item_id, value, more, fields //item_id is a ref to your Items/Product table
This allows you to link your items to your orders properly and you can do your inserts and updates without a problem.
As for your current question, you need to split it twice
$items = 1:5;6:2;13:1;
$items_arr = explode(';', $itemrs);
$new_items = array();
foreach ($iterms_arr as $item) {
$pieces = explode(':', $item);
//might want to do some error checking on whether the indices exist
$new_items[$pieces[0]] = $pieces[1];
}

SQL queries or php code?

Hello i am in a delima
Suppose that i have 50 products in a category and i want to get all the features of my products...
Ofcourse a SQL join wont help because joining would return product info many times!
So here is the question.. what is better
PLAN A
Get all the products' features in category with one SQL query and then iterate with php each feature and put it in Product.
PLAN B
For each product get the features by calling a query
Other solutions accepted!
EDIT
My table schema outline is..
A table Product which has product info(per row)
A table features which has features (feature id )
A table for features' values
And a table that has Products with their features and values
$sql1 = "SELECT * FROM products P, ". //don't use star, make sure no fields are overwritten
INNER JOIN products_to_features PTF on P.id = PTF.project_id
INNER JOIN features F F.id = PTF.feature_id
ORDER BY P.id";
$r = mysql_query($sql1, $conn);
$arr = array();
$lastProductId = -1;
while ($row = mysql_fetch_assoc($r))
{
if ($row[p_id] != $lastProductId)
{
$lastProductId = $row['p_id'];
$arr['p_id'] = array('productName' => $row['p_name'],
'productPrice' = $row['p_price'],
'productFeatures' = array(),
//other fields from product table);
}
$arr['p_id']['productFeatures']['f_id'] = array('featureName' => $row['f_name'], blah...);
}
I don't know your fields obviously, and you may want to join on feature_values so that will be more work. You can do keys/values different (ie - product names as keys. Feature-name as keys with feature-value as values, whatever you want) but the point is this is doable (and recommended) in one query.
Not Plan B.
Whatever you do this can and should be done with one or at most two total queries (one for headers, one for correctly sorted list of features + id column). Whether that query is Plan A or some unmentioned Plan C depends on your exact table structure, which isn't clear from your question.
Generally, the less database queries you have to make, the better. It greatly depends on your table structure, but I'd go with Plan A.
A query inside a loop will greatly degrade performance of your application. Avoid it at all cost.
Show us the schema. There's a strong possibility a single SQL query will solve your problem.

Categories