Tricky MySQL Insert and Update - php

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];
}

Related

Laravel storing data after chuncking them

Hello there i have 3 tables
Companies
Coupons
Categories
Company table contains
id, name, logo
category contains
id, title, logo
coupons contains
id, title, terms, company_id, category_id
the last two are for relation ship between company , category modal and coupons modal
After that bieng said, here is the case
i have sent a request to my server using api that containes Company_id.
what i want to do is get all coupons that contain this Company_id , then from those coupons i want to take all Categories
what i tried
public function fetch_Categories($Company_id)
{
//getting all coupons that containes the current company id
$Coupons = Coupons::where('company_id' , $Company_id)->get();
//Coupons variable returns two coupons which is expected
foreach($Coupons as $Coupon){
$Categroies = Categories::find($Coupon->category_id);
}
}
ok you must have noticed the problem,
i am getting two coupons and in the future i will get more and i have to get the category from each one of them using category_id column , then return it using json as a collection of categories. but the question is how should i do that *_^
if it is not clear , i am getting two coupons and i should make foreach to store each category in my variable but when you put "=" sign then you will assign value for the variable and finally you will get one category which is the last one in the foreach , what i need is a way to store all the categories using the foreach and then return them to user using json
There are many ways to achieve this. Here is one:
$categoryIds = Coupons::where('company_id', $Company_id)->pluck('category_id')->unique();
$categories = Categories::whereIn('id', $categoryIds)->get();
This is also more efficient than the foreach loop, as it only uses a single query to fetch all categories.

Insert numbers into a single field MySQL

I'm trying to insert diferent numebers (like "10 11 12") into a MySQL field (the numbers come from PHP), but when I do the query, the field only gets the first number.
For example, I do:
UPDATE profile SET subcategory = '10 11 12' WHERE userId = 1 LIMIT 1
And the DB just registers '10'.
Any way to do it?
This happen because you're updating a number, probably an integer, so mysql do the job just for the first number.
If you do this:
UPDATE profile SET subcategory = 10 WHERE userId = 1 LIMIT 1
UPDATE profile SET subcategory = 11 WHERE userId = 1 LIMIT 1
UPDATE profile SET subcategory = 12 WHERE userId = 1 LIMIT 1
You'll just update the category with the third value (12).
I suggest you a user belonging to multiple subcategories so you'll have to create another table. Eg: a table called subcategories with at least two fields: userId and subcategoryId. And then you could do something like this:
DELETE FROM subcategories WHERE userId=1
INSERT INTO subcategories (userId, subcategory) VALUES (1,10)
INSERT INTO subcategories (userId, subcategory) VALUES (1,11)
INSERT INTO subcategories (userId, subcategory) VALUES (1,12)
The first line (delete) is used just to update the user's subcategories, first you delete all older subcategories for the user and then you insert the new ones. In PHP you could use a foreach() to automatize the insertion of multiple values.
You could also have a non unique userId in the table profiles with an entry per user subcategory but it will complicate things.
I hope it could help you
From your problem I guess that the type of your subcategory is integer. What happens when you put string? It is converted. The converter convert it to first proper integer which is 10 space after 10 is considered as string.
What can solve your problem?
Chance db structure and depend on relations.
(bad idea) change the type to varchar for example and then insert will be done(DONT DO IT)
Do multiple updates(it really depends on db structure)
This very much depends on the problem you are trying to solve.
If you are just trying to store a small number of numbers then using the php join and split functions to take a list of numbers and convert to and from a string and store that in a VARCHAR.
A better way to solve the problem would be to understand the layout of your data. Try having a table that links profiles to subcategories. Two columns, one for the profile ID and one for the Subcategory ID. You might find having a search for database normalisation informative.
This presentation looks relatively informative: http://www.sqa.org.uk/e-learning/MDBS01CD/page_26.htm

Non standard sorting and navigation using MySQL and PHP

I am trying to sort the information given to me by the API of an engineering journal. I have extracted the following information into a table:
ID (integer),
Journal Entry Name (Text),
Description (Text),
Page Length (integer),
Has Media (boolean)
Each "Journal Entry" has only one ID associated with it. Each ID also has other characteristics that are not returned by the API but that I want to use to sort. They are:
Category (Things like Econ, Math, Biology. Each ID can have more than one category)
Boolean values (Things like requiring special subscriptions)
I have created a second table in the following format:
ID (integer),
Category (text),
Boolean1 (bool),
Boolean2 (bool),
Boolean3 (bool)
Since each ID can have more than one category, when this occurs another row is added to this table. The idea being that any given row only has one ID and one category in it.
What I want to do is this:
Be able to find the top ten categories when it comes to
Highest Journal Entry (ID) count
Highest Total Page Length
Highest Journal Entry count where the "Has Media" boolean is true
Create a means of navigating like "pagination" where each page shows the nth results of the aforementioned top ten.
So if I chose to Highest Journal Entry count method, the first page would be show IDs, Names, and Descriptions of all the Journal entries in the category with the highest count.
My plan has been to create a new table where the numbers one through ten are in the first column, and then populate the second column with the top ten categories. Then I can use a process similar to pagination in which the nth page only shows the values with the corresponding category from the original value. However I can't seem to be able to make this top ten list/matrix, nor do I know if it there is a better way.
Unfortunately I am not a MySQL or PHP coder by trade, and have only gotten this far by lots and lots of googling. I have been completely unable to find any guides for a navigation method like the one I want. And since I don't know the proper terminology, I am just trying random google searches at this point.
Is this the best way to go about it? Or would it be better to create a third table of some sort? Is there perhaps an easier way to do this with something that can use the PHP and MySQL code I already wrote?
Not sure I really understand what you're going for here, but my best guess is that you probably want to combine your two initial tables and have category be a set rather than an individual term so you can have a single entry per unique ID.
Then you'd just need to write calls for each of your top ten finds as needed. Since each id can have an unknown number of categories I would start with a limit of 10 and then process the returns starting with the top match, grab its categories, if there are more than 10 grab the first 10, if there are less than 10 grab what there are, update the amount you're looking for (if there were 4 then you're now looking for 6), and move on to the next best match.
Maybe something like this:
categories = null;
$delimeter = ',';
$count = 1;
$top10 = array();
$result = mysql_query("
SELECT *
FROM table_name
ORDER BY page_length DESC
LIMIT 10");
while($row = mysql_fetch_array($result) && $count <=10)
{
$categories = $row['categories'];
$id = $row['id'];
$splitcontents = explode($delimeter, $catagories);
foreach($splitcontents as $category){
if (!in_array($catagory,$top10)){
$top10[$count] = array(
'category'=>$category,
'journal_id'=>$id
);
$count++;
}
}
}

Get multiple results from db

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 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.

Categories