I have a little problem, hope you can help me... In my mysql table row named size I have:
"XS"=>"11", "S"=>"22", "M"=>"33", "L"=>"44"
I would like to get that out in an array, so I can post it to my select.
$x = mysqli_query($mysql_link, "SELECT * FROM dagenshug_produkt WHERE varenummer = '$produktid'");
while($row = mysqli_fetch_assoc($x)) {
$sizearray = array($row['size']);
print_r($sizearray);
}
This returns:
Array ( [0] => "XS"=>"11", "S"=>"22", "M"=>"33", "L"=>"44" )
But i would like
Array ("XS"=>"11", "S"=>"22", "M"=>"33", "L"=>"44")
Anyone who can help me a little?
The new db design
I post this as an answer, as it will be to loong for a comment.
I will delete it later, as it will not be a real answer to your question.
You need to redesign your database. Please read about relational database design.
One (easy) possibility is to have one table-field per size.
The downside to this design is, that if f.e. one product invents a new size called XMS you're f* and need to rewrite a lot of code.
This is where relational tables come in place. If you have an extra table that saves all the sizes per product, you're fine!
such a sizes-table could look like that:
product_sizes
----------------
id // unique id of this entry (int, auto_incement)
label // 'XS', ...
size // '22',...
product_id // the id of the product it refers to
But all that thoughts depend on your requirements that we don't know.
You asked for the wrong question. As raised in the comments, you need to redesign your database.
You don't necessarily have to develop a universal products variations (colors, sizes, matters, etc.).
Your products are in a table, they all have a unique ID. Good. In another table, store your sizes:
id: integer auto increment (PK)
size_name: 2XS, XS, L, M, L, XL, XXL, 3XL
size_description (for information purpose in the backoffice)
product_type (or product category). Remember that XL is a shirt size, whereas 10 is a shoe size.
The pivot table, which materializes the relation between your products and the sizes:
product_id
size_id
This table may contain relation data, like additional cost (sometimes large sizes are more expansive), etc.
To make it even better, you may store the association size<->product type with another table. It will be necessary in your backoffice to allow some sizes to be applied to appropriate products.
Anyway. Designing a database does not happen in phpMyAdmin. Never. There are specific tools for that, like MySQL Workbench. It will help you have full overview of your database.
You also need to know the difference between a table which represents an entity and and a table which exists for technical reasons (sorry, my vocabulary is a little limited in this case). A pivot table is not en entity, even if it can carry data (for example: the date a user was added to a group).
This is very important to know these basics, they will help you build a strong, secure, efficient and fast database.
I hope to help...
$x = mysqli_query($mysql_link, "SELECT * FROM dagenshug_produkt WHERE varenummer = '$produktid'");
$row = mysqli_fetch_assoc($x);
$arr = explode(",",$row['size']);
$a=array();
foreach($arr as $n) {
$m = explode("=>",$n);
$a[$m[0]]= $m[1];
}
print_r($a);
Related
I recently took an online PHP / MySQL course and as a way of practicing I make a stock keeping site for a paint shop.
We have a paint table:
paintID: INT, AI
paintType: varchar (e.g. metal, primer, water-based, etc.)
paintPrice: INT (e.g. 10, 15, 20)
paintColor: ???
A colors table:
colorID: INT, AI
colorName: varchar (e.g. blue, red, white, transparent, etc.)
Every paint product comes in one or more colors. So I thought of making a section within the product.php page offering all the colors as checkboxes. While this is simple enough when creating new products,
how can I store the selected colors via PHP in the MySQL database once user presses submit (and what type to give to the paintColor column)
how can I retrieve/show all the possible colors with the chosen ones selected once in 'read-only' or 'update' mode of the product page
The relationship between a Paint and a Color is Many - to - Many.
Conceptually you can have a M <-> M relationship between two entities, but in a concrete implementation, you need a "resolver" table between the two entities. I would probably call this table "paintColor"
It would have something like this in it:
paintColor
----------
paintColorID
paintID (FK to paint)
colorID (FK to color)
As you should be able to discern, this allows you to associate any number of separate color values with a specific paint. I personally don't know if this is actually a feasible design, due to questions regarding whether a specific instance of a paint/color combination doesn't need to have other attributes such that your original design with ColorID as a foreign key in Paint isn't actually what you want.
For example, if a Paint can have different prices for "Gold" vs. "Black" then you have an issue with your current model, unless you attach pricing to paintColor rather than paint. Any data model with a degree of sophistication will have many of these tradeoffs incorporated, and it may not be obvious as to what the reasoning was behind the design.
In your simple model there are probably other foreign key relationships you would want in an actual paint store application, like manufacturer. PaintType should be in a table, and not as a varchar.
MySQL actually has a special datatype that essentially allows you to embed a many to many in one column. It's called an ENUM. If you want to use it for this app, it's not the worse decision you could make, so long as you keep in mind that an ENUM violates the basic rules that all relational databases were supposed to support. For your simple application, it allows you to make a "have your cake and eat it too" which works fine in a simple application. Again, if a paint can have a different price point for 2 different colors that are otherwise the same paint, then you have a problem.
For this reason, often Many to many relationships are more appropriate, and in the way you described your app and the interface you expect, the solution is a Many to many. It's important after you make that choice that you start to learn the implications of that choice for your application.
I usually advise people to think about what the choice entails: If it's a 1-1 relationship then Entity A can have one and only one property B.
If you fill the colors table with preset colors yourself, you can allow the user to select a color from your predefined entries and you store the colorID from the colors table in the the row as foreign key using color in the paint table when you store the user's entry and to retrieve do a left out join on the color table where the ID in the paint row with ID on the row in the color table. The statement would look like...
Junction table
CREATE TABLE juct_paint_color (
paint_key int not null,
color_key int not null,
FOREIGN KEY(paint_key) references paint(paintID),
FOREIGN KEY(color_key) references color(colorID)
)
New insert statement for junction table after you insert the new paint.
INSERT INTO juct_paint_color(paint_key, color_key) VALUES(?, ?)
NEW select statement, you can keep the select the paint however you were doing so before but the two get the color simply used the paintID column from the paint table like so.
SELECT t2.* FROM juct_paint_color t1
LEFT OUTER JOIN color t2
ON t2.colorID = t1.color_key WHERE t1.paint_key = ?;
you could use a transaction or stored procedure in you database to ensure that a new paint row is never inserted without a proper entry to the junction_table, but if you constrict the user input it probably won't be necessary.
I have a Laravel application using a MySQL database with millions of records across multiple tables which look as follows when simplified:
Table: products
Columns: product_id name price stockist colour brand stock date_added
Table: stockists
Columns: stockist_id name phone email post_code stock
Table: categories
Columns: category_id name slug level
Table: category_product
Columns: category_id product_id
Users are able to search for products based on a large number of criteria (approximately 15), encompassing almost all product-related data. A sample search may look like this:
Return the first 50 products which:
- cost more than £5
- cost less than £30
- are branded by 'Apple', 'Samsung', or 'LG'
- belong to the categories 'usb chargers' or 'batteries' but not 'cases' or 'covers' or 'in-car chargers'
- were added less than two weeks ago
I want to be able to store the search parameters against the user that made them in order for them to be able to rerun the search multiple times. From my research the solutions I've come across include views which I don't believe will work as they don't accept parameters and prepared statements which wouldn't work either as they cannot be saved. That leaves stored procedures or saving to a dedicated table with a column for each parameter. I'm leaning towards the latter of the two, although I can see that getting very messy very quickly. Can someone point me towards the best solution to the problem? Thanks.
If you don't want to maintain a list of filter columns, you can use a key-value store pattern.
table: user_search_criteria
columns: user_id, key, value
$criterium = new UserSearchCriteria();
$criterium->user_id = $user->id;
$criterium->key = 'price';
$criterium->value = '<= 100';
$criterium->save();
But I guess you don't have to remember criteria for a very long time, so I'd use Redis for this.
Redis::set('criteria.' . $username, $criteria);
$criteria = Redis::get('criteria.' . $username);
You may use $_SESSION.
$_SESSION['seach_critera'] = json_encode($criterea_array);
https://www.php.net/manual/en/reserved.variables.session.php
I want to design a little on-line store. The website should have every detail about products. Since I am beginner I stuck at designing good database design.
There are many different products: Cellphone, Laptop, Stove, Bag, etc. Each of these products need different details. I am not going to design many different table for each, So one table (product) going to have all products.
But How I manage details? I couldn't find good topic on Google so I started my own poor design. This is my draft design:opps can not post image
Product stores product name.
Product_category defines type of product, like: mobile or book. each product belongs to one product category
Product_category_detail stores product attributes like color, wight,
battery life etc. each product_category_details belongs to one
product_category.
Product_detail keeps values of detail like 3 hour
for battery life, or 400g for wight. each of this belogns to one
product category detail and product.
I can store all details in Var-char.
Is it good? any suggestion!
It's better to have type of detail. like varchar for color and int for wight.
I am thinking on another field in product_catefory_datail named attr_type so I can change convert in php.
Any idea? tnx
I suggest you to use product table only to keep generic information about product, than have product_attributes table:
ID (INT|Unique) | product_id (INT) | name (VARCHAR) | value (VARCHAR) | type (INT: predefined constant values)
This is where you do need the Entity Attribute Value (EAV) model. If you need different data types then you need additional columns to specify the data type and for each data type: eg type specified as 'string' so select the string_value column, 'number' select the numeric_value column. That means CASE statemenst everywhere. Makes the whole thing horrible to work with.
an online store is very complex, and not really a beginners task. It wont be scalable and since you dont know yet how many variations you need you'll end up with adding new tables and columns until it gets too complex. Stores usually have a EAV model for this; http://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model .
I had this similar issue while doing a project, and developed tables which solved my problem . Hope this helps you too.
product_table
pt_id,name,category
product_category_table
pct_id,name,desc
detail_fields
pf_id,field_name
product_detail_fields
pdf_id,pt_id,pf_id,default_value
product_detail_fields_values
pdfv_id,pdf_id,value,user_id //here pdf_id is fk of product_detail_fields
If you have multiple users, make use of user_id, else ignore it.
Thanks for reading, I hope this makes sense! I am trying to modify a bespoke CMS which gives different product options and lets you set various attributes based on combinations of those options. These are getting pulled from a mySQL database. For example, a t-shirt might have:
Colour Size
------ ----
Red Small
Red Medium
Blue Small
Blue Medium
Each colour and size would have a unique ID so red = 1, blue = 2 and small = 3, medium = 4. Colour and Size would each have a parent id, so colour = 1, size = 2.
At the moment I am storing a string in a database table in the database that identifies each combination (e.g. Red + small would be &1=1&2=3). This string then associates this combination of options with various attributes: price, stock code etc.
However the problem comes when we want to add a new option group to the mix, say sleeve length. At the moment this would mean having to go through the strings and changing them to also include the new option. This seems like a very inefficient and long-winded way to be doing this!
So (eventually!) my question is - is there a better way I can be doing this ? I need to ensure that there is no real limit on the number of option groups that can be added, as well as letting new option groups be added at any time.
Thanks in advance for your help.
Stuart
I would counter instead with asking you, why would you want to store that in the first place?
Cartesian products are a controller issue, not a domain model one. Your domain model (your database) should only care to keep the data in a normalized fashion (or as close as it's feasible), let the database system do the joins as needed (inner join in sql), that's what they're optimized to do in the first place.
So, not having come from a database design background, I've been tasked with designing a web app where the end user will be entering products, and specs for their products. Normally I think I would just create rows for each of the types of spec that they would be entering. Instead, they have a variety of products that don't share the same spec types, so my question is, what's the most efficient and future-proof way to organize this data? I was leaning towards pushing a serialized object into a generic "data" row, but then are you able to do full-text searches on this data? Any other avenues to explore?
split products and specifications into two tables like this:
products
id name
specifications
id name value product_id
get all the specifations of a product when you know the product id:
SELECT name,
value
FROM specifications
WHERE product_id = ?;
add a specification to a product when you know the product id, the specification's name and the value of said specification:
INSERT INTO specifications(
name,
value,
product_id
) VALUES(
?,
?,
?
);
so before you can add specifications to a product, this product must exist. also, you can't reuse specifications for several products. that would require a somewhat more complex solution :) namely...
three tables this time:
products
id name
specifications
id name value
products_specifications
product_id specification_id
get all the specifations of a product when you know the product id:
SELECT specifications.name,
specifications.value
FROM specifications
JOIN products_specifications
ON products_specifications.specification_id = specifications.id
WHERE products_specifications.product_id = ?;
now, adding a specification becomes a little bit more tricky, cause you have to check if that specification already exists. so this will be a little heavier than the first way of doing this, since there are more queries on the db, and there's more logic in the application.
first, find the id of the specification:
SELECT id
FROM specifications
WHERE name = ?
AND value = ?;
if no id is returned, this means that said specification doesn't exist, so it must be created:
INSERT INTO specifications(
name,
value
) VALUES(
?,
?
);
next, either use the id from the select query, or get the last insert id to find the id of the newly created specification. use that id together with the id of the product that's getting the new specification, and link the two together:
INSERT INTO products_specifications(
product_id,
specification_id
) VALUES(
?,
?
);
however, this means that you have to create one row for every specific specification. e.g. if you have size for shoes, there would be one row for every known shoe size
specifications
id name value
1 size 7
2 size 7½
3 size 8
and so on. i think this should be enough though.
You could take a look at using an EAV model.
I've never built a products database, but I can point you to a data model for that. It's one of over 200 models available for the taking, at Database Answers. Here is the model
If you don't like this one, you can find 15 different data models for Product oriented databases. Click on "Data Models" to get a list and scroll down to "Products".
You should pick up some good design ideas there.
This is a pretty common problem - and there are different solutions for different scenarios.
If the different types of product and their attributes are fixed and known at development time, you could look at the description in Craig Larman's book (http://www.amazon.com/Applying-UML-Patterns-Introduction-Object-Oriented/dp/0131489062/ref=sr_1_1/002-2801511-2159202?ie=UTF8&s=books&qid=1194351090&sr=1-1) - there's a section on object-relational mapping and how to handle inheritance.
This boils down to "put all the possible columns into one table", "create one table for each sub class" or "put all base class items into a common table, and put sub class data into their own tables".
This is by far the most natural way of working with a relational database - it allows you to create reports, use off-the-shelf tools for object relational mapping if that takes your fancy, and you can use standard concepts such as "not null", indexing etc.
Of course, if you don't know the data attributes at development time, you have to create a flexible database schema.
I've seen 3 general approaches.
The first is the one described by davogotland. I built a solution on similar lines for an ecommerce store; it worked great, and allowed us to be very flexible about the product database. It performed very well, even with half a million products.
Major drawbacks were creating retrieval queries - e.g. "find all products with a price under x, in category y, whose manufacturer is z". It was also tricky bringing in new developers - they had a fairly steep learning curve.
It also forced us to push a lot of relational concepts into the application layer. For instance, it was hard to create foreign keys to other tables (e.g. "manufacturer") and enforce them using standard SQL functionality.
The second approach I've seen is the one you mention - storing the variable data in some kind of serialized format. This is a pain when querying, and suffers from the same drawbacks with the relational model. Overall, I'd only want to use serialization for data you don't have to be able to query or reason about.
The final solution I've seen is to accept that the addition of new product types will always require some level of development effort - you have to build the UI, if nothing else. I've seen applications which use a scaffolding style approach to automatically generate the underlying database structures when a new product type is created.
This is a fairly major undertaking - only really suitable for major projects, though the use of ORM tools often helps.