组合来自 MySQL 结果的多个产品属性


Combine multiple product attributes from MySQL result

我有一个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 **] 
  }

使用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" />;
}

从机械上讲,您可能需要更多的东西,包括表单的完整形成和提交时的处理表单,但这应该可以让您入门。

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


请停止使用mysql_*函数。这些扩展已在 PHP 7 中删除。了解PDO和MySQLi的预准备语句,并考虑使用PDO,这真的很容易。

首先,我建议使用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.'">';
}