从sql输出php中的数据

时间:2016-05-02 15:17:42

标签: php mysql

我想从php

中输出mysql的分组数据

sql数据库: enter image description here

我有一个sql语句,根据to_id为4对内容进行分组。

sql statement: select group_concat(messg) from my_table  where to_id = 4   
group by from_id;

我想查看php中的消息,以便我得到:

1. get: 2messages  from_id 1(messages: TRUELOVE, hadi when)
2. get: 1 msg from_id 2(message: cutie)
3. get: 1 msg from_id 3(message: true love)

连接数据库的声明:

<?php
$con = mysqli_connect("localhost", "root","","bmcs" );

if(mysqli_connect_errno()){

  echo "Failed to connect to database". mysqli_connect_error();
}

1 个答案:

答案 0 :(得分:1)

使用mysqli shoudl是这段代码

  <?php 
    $sql = "SELECT 
            group_concat(messg) as msg, from_id, time_sent
            from my_table 
            where to_id = 4   
            group by from_id"; 

        if ($result = $mysqli->query($sql)) { 
            while($obj = $result->fetch_object()){ 
                echo $obj->msg . '<br />'; 
                echo $obj->from_id . '<br />'; 
                echo $obj->time_sent. '<br />'; 


            } 
        } 
        $result->close(); 
        unset($obj); 
        unset($sql); 
        unset($query); 

?>