首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 繪製動態柱狀圖 (純 HTML/CSS 實作)

     編輯:PHP 相關知識

PHP 繪製動態柱狀圖 (純 HTML/CSS 實作)

無需引入 GD、Chart.js 等圖形庫,利用 PHP 查詢統計數據,配合 HTML `

` 寬度/高度與 CSS 即可快速產生直觀的柱狀圖。適用於後台簡易報表、儀表板原型。

核心邏輯

  1. 查詢最近一個月總筆數、初審通過、複審通過、終審通過四項指標。
  2. 2. 以最大值為基準,計算各柱高度百分比 (或固定最大像素高度)。 3. 輸出 `` 列,每欄包含數值標籤 + `
    `,透過 `style="height: {$pct}%"` 控制高度。

    完整範例

    <?php
    // 計算上個月同一天
    function lastMonthToday($time) {
        $last = mktime(date('G',$time), date('i',$time), date('s',$time), date('n',$time), 0, date('Y',$time));
        $lastDay = date('t', $last);
        return $lastDay < date('j',$time)
            ? date('Y-m-t H:i:s', $last)
            : date('Y-m-'.date('j',$time).' H:i:s', $last);
    }
    
    require __DIR__.'/../../config.php'; // 假設回傳 PDO $db
    $end   = date('Y-m-d');
    $begin = lastMonthToday(strtotime($end));
    
    $base = "SELECT COUNT(*) FROM newpro WHERE p_date > '$begin' AND p_date < '$end'";
    $total      = $db->query($base)->fetchColumn();
    $firstPass  = $db->query("$base AND is_pa_check_first=1")->fetchColumn();
    $secondPass = $db->query("$base AND is_pa_check_first=1 AND is_pa_check_second=1")->fetchColumn();
    $finalPass  = $db->query("$base AND is_pa_check_first=1 AND is_pa_check_second=1 AND is_pa_check_third=1")->fetchColumn();
    
    $maxVal = max($total, $firstPass, $secondPass, $finalPass);
    $scale  = 200 / $maxVal; // 最大高度 200px
    ?>
    <!DOCTYPE html>
    <html><head><meta charset="utf-8">
    <style>
    .chart-wrap { display:flex; align-items:flex-end; gap:20px; height:220px; padding:20px; }
    .bar { width:50px; background:#669900; transition:height .3s; }
    .label { text-align:center; margin-top:4px; font-weight:bold; }
    .axis { display:flex; justify-content:space-between; width:260px; margin:0 auto; color:#666; }
    </style></head><body>
    <h3>近一個月審核統計</h3>
    <div class="chart-wrap">
        <div><div class="bar" style="height:px"></div><div class="label">總計: </div></div>
        <div><div class="bar" style="height:px"></div><div class="label">初審: </div></div>
        <div><div class="bar" style="height:px"></div><div class="label">複審: </div></div>
        <div><div class="bar" style="height:px"></div><div class="label">終審: </div></div>
    </div>
    <div class="axis"><span>0</span><span></span></div>
    </body></html>

    進階建議

    • 加入動畫:CSS `transition: height .5s ease-out`。
    • 資料量大時改用 SVG 或 Canvas (Chart.js, ApexCharts) 繪製。
    • 3. Y 軸刻度、Tooltip、響應式斷點均可用 CSS/JS 增強。
    1. 上一篇文章:
    2. 下一篇文章:
    Copyright © 程式碼之家 All Rights Reserved