将mysql查询中变量php(while/loop)的结果保存在一行中

4si2a6ki  于 2021-06-16  发布在  Mysql
关注(0)|答案(2)|浏览(885)

查询时,结果由多个值组成(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/">;
}

此查询/while的结果是:

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
vq8itlhq

vq8itlhq1#

把代码的sql注入漏洞放在一边。可以将结果展平为一列,如下所示:

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

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

xvw2m8pv2#

你可以直接用选择键得到结果

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,可以使用insert/select

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有风险)

相关问题