2016-10-14 21:49

如何在php中将数据库中的多个列合并为一个结果? 那可能吗?


i have big database table and i need result from multiple columns into one. its about how much people is checked from some conturies and every contry has own column. here is some of it: rs_turista, rs_nocenja, agencija_turista, agencija_nocenja, at_turista, at_nocenja, be_turista, be_nocenja, ba_turista... they is checking every day. i need to sum it all in php for report. is that posible?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dtq26360 dtq26360 5年前

    Don't do it in PHP, that's needlessly selecting too much data from a database. All you gotta do is use a SUM() and + like so:

    SELECT SUM(column1) + SUM(column2) + SUM(column3) + ... AS total
    FROM table
    WHERE <filters for a date or other requirements>
    点赞 评论 复制链接分享
  • douben8492 douben8492 5年前

    Yes it is possible. Fetch data using mysqli_fetch_assoc and then iterate through the diferent keys of the array (each row is an array).

    Will be something like this:

    $conn= mysqli_connect("mydbhost", "my_user", "my_password", "mydatabase");
    $result= mysqli_query($conn, "SELECT rs_turista, rs_nocenja, agencija_turista, agencija_nocenja, at_turista, at_nocenja, be_turista FROM mytable");
    $ttl= 0;
    while ($row = mysqli_fetch_assoc($result)) {
        foreach($row as $key => $value) {
            $ttl += $value;
    echo $ttl;

    Of course, you need to do some error checking on connection, but at last, the basic schema is like this.

    Look at here for more information: http://php.net/manual/en/mysqli-result.fetch-assoc.php

    点赞 评论 复制链接分享