dongyu9667 2015-11-02 06:51
浏览 39
已采纳

在php中显示表中的数据

$sql=" SELECT * from `request_location` where requestid = '".$requestid."' ";
    $result = mysqli_query($con, $sql);
    if(mysqli_num_rows($result)>0)
        {
            echo "(";
            while($row = mysqli_fetch_assoc($result))
                {
                    echo  $row["location_tag"]; 
                    echo ",";
                }
            echo ")";   
        }

I have this above code that displays data in a format where the result is placed within round brackets and each term is separated by a comma

The result that i am getting is like this

(a,b,c,)

Although it seems to be fine but i want that the comma should not appear after c as it is the last term like this

(a,b,c)

Can anyone please tell how to remove comma after the last element

  • 写回答

5条回答 默认 最新

  • doushanlv5184 2015-11-02 06:53
    关注

    Solution 1:

    You can do it using implode() function and array().

    Logic behind it:

    1) Take a blank array.

    2) Fetch the results the same way as existing.

    3) Append results to the array.

    4) After the loop ends implode() the array with a comma.

    5) Add a prepending and post pending ( and ) to the result.

    sql=" SELECT * from `request_location` where requestid = '".$requestid."' ";
    $result = mysqli_query($con, $sql);
    $arr = array();
    if(mysqli_num_rows($result)>0) {
      while($row = mysqli_fetch_assoc($result)) {
        $arr[] = ["location_tag"]; 
      }
    }
    echo ! empty($arr) ? '(' . implode(',', $arr) . ')' : '';
    

    Solution 2:

    Use MYSQL's GROUP_CONCAT() (if you want to fetch only one field from database table).

    sql=" SELECT GROUP_CONCAT(location_tag) from `request_location` where requestid = '".$requestid."' ";
        $result = mysqli_query($con, $sql);
        $ids = '';
        if(mysqli_num_rows($result)>0) {
          while($row = mysqli_fetch_assoc($result)) {
            $ids = ["location_tag"]; 
          }
        }
    
    echo ! empty($ids) ? '(' . $ids . ')' : '';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示