将来自MySQL查询的变量PHP(while / loop)的结果保存在一行中

时间:2019-01-04 16:11:24

标签: php mysql variables while-loop

查询时,结果由多个值(WHILE / LOOP)组成,例如:

   $query_sku = mysqli_query($connect, "SELECT t.column_name
        FROM skus AS s
            INNER JOIN table AS t ON t.column_id = s.column_id
                WHERE s.id_sku = '{$id_sku}'");
WHILE($reg = mysqli_fetch_object($query_sku )){
  $variable = $reg->column_name;
echo "<br/">;
}

此查询/查询的结果为:

BATERIA  
PARA
CÂMERA
CANON
PowerShot ELPH 330 HS

当我将值保存在数据库中时,这些值将保存在不同的行中。

但是,我希望您将其保存为一行:

BATERIA PARA CÂMERA CANON PowerShot ELPH 330 HS

我该怎么做?谢谢!

我已经尝试这样做:

while($reg = mysqli_fetch_object($query_sku ))
    $variable .= " ".$reg->column_name;

但是,结果是重复相同的值:

PowerShot ELPH 330 HS BATTERY (RECHARGEABLE)PowerShot ELPH 330 HS BATTERY (RECHARGEABLE) CAMERAPowerShot ELPH 330 HS BATTERY (RECHARGEABLE) CAMERA CANON

2 个答案:

答案 0 :(得分:0)

您可以使用select直接获得结果

SELECT group_concat( t.column_name  SEPARATOR ' ')
FROM skus AS s
INNER JOIN table AS t ON t.column_id = s.column_id
WHERE s.id_sku = '{$id_sku}'

对于插入,您可以使用插入/选择

insert into my_table  (my_col)
SELECT group_concat( t.column_name  SEPARATOR ' ')
FROM skus AS s
INNER JOIN table AS t ON t.column_id = s.column_id
WHERE s.id_sku = '{$id_sku}'

无论如何,您应该查看绑定参数,并避免在SQL中使用php var(您可能会冒sqlinjectio的风险)

答案 1 :(得分:0)

抛开代码的SQL注入漏洞。您可以将结果展平到这样的一列:

$variables = [];
while($reg = mysqli_fetch_object($query_sku)){
  $variables[] = $reg->column_name;
}

$oneColumn = implode(' ', $variables);