I could not figure out how to solve this:
Database:
+-------+-------------+------+
| id | ArticleNr | Size |
+-------+-------------+------+
| 1 | AN111 | L |
| 2 | AN111 | XL |
| 3 | AN222 | M |
+-------+-------------+------+
sql = "SELECT * FROM table GROUP BY article_number"
$result = $site_db->query($sql);
my_array = array();
while ($row = $site_db->fetch_array($result)) {
$article_number = $row['article_number'];
$size = $row['size'];
$my_array[${'article_number'}] .= $row['size'];
}
As results I got this:
AN111: L
AN222: M
However I want something like this:
AN111: L - XL
AN222: M
Any help will be appreciated
I am guessing you want something like this:
SELECT article_number, GROUP_CONCAT(DISTINCT size)
FROM table
GROUP BY article_number;
Unless you really, really, really know what you are doing, don't use SELECT *
with GROUP BY
. It is not allowed in most other databases and is usually a sign of broken code.
The returned value from the sql will be the first answer that matches the grouped article number if there are multiple entries for the article number, hence the returned L
I would ORDER BY article_number
and forget the GROUP BY clause.
This would return all of the answers to the php parser
$sql = "SELECT * FROM table ORDER BY article_number"
$result = $site_db->query($sql);
$my_array = array();
$article_number = '';
$size = '';
while ($row = $site_db->fetch_array($result)) {
if($row['article_number']!=$article_number) {
$article_number = $row['article_number'];
$size = $row['size'];
} else {
$article_number = $row['article_number'];
$size .= ' - '.$row['size'];
}
$my_array[$row['article_number']] = $row['size'];
}
SELECT *
FROM my_table
ORDER
BY articlenr
, FIELD(size,'XS','S','M','L','XL','XXL');
The rest of this problem can be solved with a simple PHP loop.