dongliping003116 2014-01-19 03:48
浏览 14
已采纳

使用while获取查询结果到数组中

I'm very new to PHP. In fact, I just finished reading an introduction to it, so excuse me if I explain things poorly as I'm very inexperienced. I'm learning how to connect to databases using PDO, and I want to dump the results of a query into an array so that a graph library I want to use can chart the number of visits to a particular place in the last day. Everything else works fine, and the query returns the expected results when ran using phpMyAdmin. I can't use the results directly from the query, as the library doesn't understand it for some reason.

Because of this, I had the idea to use while to iterate through the results and add the information to an array. But for some reason, only the latest result is being added. I know I'm missing something really simple here, but I'm still too ignorant to know what it is I need to do.

# Establish the connection
$conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->query('SELECT HOUR( TIMESTAMP ) AS HOUR , COUNT( detected_key ) AS num_rows
                            FROM Visitors
                            GROUP BY HOUR( TIMESTAMP ) 
                            LIMIT 0 , 24');

while($row = $data->fetch(PDO::FETCH_ASSOC)) {
$visit = array (
$row['HOUR'] => $row['num_rows']
);
}
  • 写回答

1条回答 默认 最新

  • dongxu4023 2014-01-19 03:51
    关注

    Rewrite your while like this.

    while($row = $data->fetch(PDO::FETCH_ASSOC)) {
    $visit[$row['HOUR']]= $row['num_rows'];
    }
    
    print_r($visit); // "prints your array"
    

    You are getting the last value because you are overwritting each and everytime.

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

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序