duanliao6077 2016-03-04 16:25
浏览 113
已采纳

货币美元符号:最好在SQL查询中连接,还是使用PHP?

I heard somewhere that it's better to have the server perform tasks, such as concatenation, but does that also apply to aesthetic stuff as well? How about using FORMAT(val, 2) vs NUMBER_FORMAT(val, 2)?

It seems like double the work, because I will still need to fetch the non-concatenated value(s) to perform other calculations, like getting the sum of all rows.

i.total AS total,
CONCAT('$', FORMAT(i.total, 2)) AS nice_total,
... etc


$sum_total = 0;
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
    $sum_total += $row['total']; #calculate sum of all rows
    ?>
    <tr>
        <td><?php echo $row['nice_total']; ?></td> <!-- Example 1 -->
    </tr>
    <?php
}
?>
<tr>
    <td>$<?php echo NUMBER_FORMAT($sum_total, 2); ?></td>
</tr>

VS

i.total AS total,
... etc


$sum_total = 0;
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
    $sum_total += $row['total']; #calculate sum of all rows
    ?>
    <tr>
        <td>$<?php echo NUMBER_FORMAT($row['total'], 2); ?></td> <!-- Example 2 -->
    </tr>
    <?php
}
?>
<tr>
    <td>$<?php echo NUMBER_FORMAT($sum_total, 2); ?></td>
</tr>

I only have 4 fields to fetch with a similar structure (subtotal, tax1, tax2, total), but to fetch the same column twice for concatenation (or even formatting) feels wrong, especially if I have tons of rows; i'm just not sure how to measure the pros/cons. I do like to keep my logic as close together as possible, if that matters.

Thanks!

  • 写回答

1条回答 默认 最新

  • douxiong4250 2016-03-04 17:03
    关注

    "It seems like double the work, because I will still need to fetch the non-concatenated value(s) to perform other calculations, like getting the sum of all rows."

    Go with your gut here. Why make the DB server work when you can just echo the "$" as you are in your plain HTML? The only thing I that might be wrong with the 2nd approach is that you'll have a "$" printed regardless of whether or not there is an actual value yielded by $row['total'] ...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误