mysql_stat() 是 PHP 早期擴展提供的輕量級函數,用於快速獲取 MySQL 服務器核心運行狀態字符串。本文詳細講解語法、參數、返回格式、解析方法及現代監控替代方案。
string mysql_stat([resource $link_identifier = NULL])
$link_identifier — 可選,MySQL 連接資源。省略時使用最近打開的連接。false。典型輸出範例:
Uptime: 99410 Threads: 1 Questions: 162
Slow queries: 0 Opens: 0 Flush tables: 1
Open tables: 0 Queries per second avg: 0.002
| 字段 | 含義 | 關注重點 |
|---|---|---|
Uptime | 服務器運行秒數 | 排查意外重啟 |
Threads | 當前連接線程數 | 連接池使用率、最大連接數壓力 |
Questions | 啟動以來總查詢數 | QPS 計算基數 |
Slow queries | 慢查詢數量 | 性能調優核心指標 |
Opens | 打開表數量 | table_open_cache 效果 |
Flush tables | FLUSH TABLES 執行次數 | 運維操作追蹤 |
Open tables | 當前打開表數 | 佔用情況 |
Queries per second avg | 平均 QPS | 負載基線 |
<?php
$con = mysql_connect("localhost", "hello", "321");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db", $con);
$status = mysql_stat();
if ($status !== false) {
echo "MySQL 狀態:\n$status";
} else {
echo "獲取狀態失敗: " . mysql_error();
}
?>
function parse_mysql_stat($stat_str) {
$metrics = [];
$lines = explode("\n", $stat_str);
foreach ($lines as $line) {
$parts = explode(" ", trim($line));
foreach ($parts as $part) {
if (strpos($part, ':') !== false) {
list($key, $val) = explode(':', $part, 2);
$metrics[trim($key)] = trim($val);
}
}
}
return $metrics;
}
// 使用
$metrics = parse_mysql_stat(mysql_stat());
echo "QPS: " . $metrics['Queries per second avg'];
echo "慢查詢: " . $metrics['Slow queries'];
mysql_stat() 及 mysql_* 系列函數 **PHP 5.5 棄用、PHP 7.0 移除**。InnoDB_buffer_pool、Innodb_row_lock、Created_tmp_tables 等核心指標。SHOW STATUS 或 SHOW GLOBAL STATUS 獲取完整狀態變量(超過 300 項)。$mysqli = new mysqli("localhost", "user", "pass", "db");
$result = $mysqli->query("SHOW GLOBAL STATUS");
$metrics = [];
while ($row = $result->fetch_assoc()) {
$metrics[$row['Variable_name']] = $row['Value'];
}
// 核心指標即時獲取
echo "QPS: " . ($metrics['Questions'] / $metrics['Uptime']);
echo "緩存命中率: " . (1 - $metrics['Innodb_buffer_pool_reads'] / $metrics['Innodb_buffer_pool_read_requests']);
// ... 300+ 指標任意查
mysql_stat() 適合舊專案快速診斷,但**指標極少、已棄用**。現代開發請直接使用 SHOW GLOBAL STATUS 獲取全量指標,並接入 Prometheus/PMM 等專業監控體系,構建可觀測的 MySQL 運行保障體系。