【问题标题】:Combine multiple product attributes from MySQL result结合 MySQL 结果中的多个产品属性
【发布时间】:2016-05-01 21:07:58
【问题描述】:

我有一个 mySQL 表,其中包含多行产品属性,每个属性都与特定的属性类别 (id_attrib_cat) 相关联。

用户应该为每个产品属性组合定义一个价格,所以我需要一个循环来创建一个属性表,每行末尾都有一个价格输入。

属性类别值对于排除来自同一类别的属性进行组合很重要。

我怎样才能做到这一点?

编辑

属性类别示例:值

格式:方形、圆形

尺码:S、M、L

颜色:白、蓝、黑、黄

属性组合表示例(下面的循环应该这样做):

  1. 正方形 + S + 白色 = [价格输入]
  2. 方形 + S + 蓝色 = [价格输入]
  3. 正方形 + S + 黑色 = [价格输入]

[...]


$q = mysql_query("SELECT id_attrib_cat, id_attrib, name FROM cms_products_attribs WHERE id_product=10 ORDER BY id_attrib ASC"); 

  while ($row = mysql_fetch_array($q, MYSQL_NUM)) {

      [** attribute combination + price input code **] 

  }

【问题讨论】:

标签: php mysql arrays while-loop


【解决方案1】:

在查询本身中连接,使用CONCAT

SELECT CONCAT(`id_attrib_cat`, ' ', `id_attrib`) AS `attributes`, `name` 
FROM `cms_products_attribs` 
WHERE `id_product`=10 
ORDER BY `id_attrib` ASC

这对你来说意味着你将有一个来自行的输出:

while ($row = mysql_fetch_array($q, MYSQL_NUM)) {
  $attribs = $row['attributes'];
  echo $attribs . '<input name="price" type="text" />;
}

从机制上讲,您可能需要的远不止这些,包括表单的完整形成和提交时处理表单,但这应该可以帮助您入门。

如果可以的话,您应该始终让您的数据库完成它所设计的繁重工作。


stop using mysql_* functionsThese extensions 已在 PHP 7 中删除。了解 preparedPDOMySQLi 语句并考虑使用 PDO,it's really pretty easy

【讨论】:

  • 这是比我的杰伊更好的答案。经验很重要:)
  • 最棒的是你每天都在获得经验@MDChaara :)
  • 谢谢,但这只是列出与产品相关的属性......我需要将它们组合起来,以便用户能够为每个产品组合定义价格 - 我已经在我的帖子中添加了信息。谢谢。
  • @Luis:你的意思是像一个嵌套循环?
  • @Luis 您可以为每一行输出一个表单。然后,当用户为每个表单填写数据时,他们可以一次提交一行或整个表单的数据。您想让我们为您编写所有代码吗?
【解决方案2】:

首先,我建议使用 PDO。 mysql_query 在 PHP 5.5.0 中被弃用,在 PHP 7.0.0 中被移除

您的查询应该是这样的:

$q  =   $db->prepare("SELECT `id_attrib_cat`, `id_attrib`, `name` FROM cms_products_attribs WHERE `id_product`=:id_product ORDER BY `id_attrib` ASC");
$q->execute(array(':id_product'=>"10"));

我相信查询会返回多行。而不是while,使用foreach:

foreach($q as $row){

$id_attrib_cat  =   $row['id_attrib_cat'];
$id_attrib      =   $row['id_attrib'];
$name           =   $row['name'];

//Price Input goes here
echo $id_attrib_cat.'<br>';
echo $id_attrib.'<br>';
echo $name.'<br>';
echo '<input type = "text" name="'.$id_attrib.'">';
}

【讨论】:

    猜你喜欢
    • 2020-02-12
    • 2021-06-20
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多