php - 如何在 while 循环中连接表中的两列值,如 -product_name(product_quantity), ..... 并存储在变量中

标签 php mysql function

我有一个包含两列的表:多行的product_name 和product_qty

我想要输出为:

产品名称(产品数量).........

喜欢这个

产品_一(2)、产品_二(4)、产品_三(1)

我正在尝试这种方法:

require 'config.php';
$grand_total = 0;
$items = array();
$qty = array();
$allItems ='';
$stmt = $conn->prepare("SELECT * FROM cart");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
    $grand_total +=$row['total_price'];
    $items[] = $row['product_name'];
    $qty[] = $row['qty'];
}
$array = array_combine($items, $qty);
foreach ($array as $key => $value) {
    $allItems .= $key."(".$value."), ";
}

输出为: 产品一(2),产品二(4),产品三(1),

但我不想在最后加上逗号......

最佳答案

好的,答案就在您的问题标题中。 :),如下:

select concat(product_name,'(',product_qty,')') as result from my_table;

数据示例如下:

mysql> select * from my_table;
+---------------+-------------+
| product_name  | product_qty |
+---------------+-------------+
| product_one   |           2 |
| product_two   |           4 |
| product_three |           1 |
+---------------+-------------+
3 rows in set (0.00 sec)

mysql> select concat(product_name,'(',product_qty,')') as result from my_table;
+------------------+
| result           |
+------------------+
| product_one(2)   |
| product_two(4)   |
| product_three(1) |
+------------------+
3 rows in set (0.00 sec)

关于php - 如何在 while 循环中连接表中的两列值,如 -product_name(product_quantity), ..... 并存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56404176/

相关文章:

php - 修改mysql数据库以提高效率

php - 如何将数据从sqlite发送到MYSQL

php - 如何通过向数据库提交表单将 youtube 短 url 更改为可嵌入值?

javascript - 当我只知道标题时如何将文本插入文本区域

c - 从一个文件读取并打印到另一个文件

php - UTF-8贯穿始终

php - 给定 2 个参数,不管顺序如何,创建一个唯一的字符串

javascript - 使用 mootools 从 mysql 获取图像 url

c++ - 自动提交被禁用并且永远不会回滚会发生什么?

javascript - Coffeescript:从同一对象中的函数调用数组函数