Files
lgp-admin-plus-api/scripts/db-check.php
LQ bcf54c2727 初始化
缺陷:主题配色需要优化整体的同风格
2026-08-14 23:21:21 +08:00

65 lines
2.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* 数据库连通性自检:只输出通/不通与来源文件名,绝不打印任何凭据。
*
* 环境重建后 mysql 容器换了名字,新后端 .env 里的账号密码可能已失效。
* 这里依次拿几个项目的 .env 试连,用来定位到底哪套凭据还有效。
*
* 用法php scripts/db-check.php
*/
$candidates = [
'lgp-admin-plus-api/.env' => __DIR__ . '/../.env',
'lgp-api/.env' => __DIR__ . '/../../lgp-api/.env',
'lgp-wx-api/.env' => '/www/sites/lgp-wx-api/index/lgp-wx-api/.env',
];
function readEnv(string $path): array
{
if (!is_file($path)) {
return [];
}
$values = [];
foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
$line = trim($line);
if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) {
continue;
}
[$key, $value] = explode('=', $line, 2);
$values[trim($key)] = trim(trim($value), "\"'");
}
return $values;
}
$target = $argv[1] ?? null;
// 环境重建后 host 也可能变了,所以每套凭据都对「自带 host」和「当前 mysql 容器」各试一次
$hosts = ['mysql8'];
foreach ($candidates as $label => $path) {
$env = readEnv($path);
if (empty($env)) {
echo str_pad($label, 32) . " 文件不存在\n";
continue;
}
$envHost = $env['DB_HOST'] ?? '127.0.0.1';
foreach (array_unique([$envHost, ...$hosts]) as $host) {
$port = $env['DB_PORT'] ?? '3306';
$db = $target ?: ($env['DB_DATABASE'] ?? '');
$user = $env['DB_USERNAME'] ?? 'root';
try {
$pdo = new PDO(
"mysql:host={$host};port={$port};dbname={$db};charset=utf8mb4",
$user,
$env['DB_PASSWORD'] ?? '',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 5]
);
$count = $pdo->query('SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE()')->fetchColumn();
echo str_pad($label, 32) . " 可连接 host={$host} db={$db} 表数={$count}\n";
} catch (Throwable $e) {
$reason = preg_replace('/using password: (YES|NO)/', 'using password: ***', $e->getMessage());
echo str_pad($label, 32) . " 连不上 host={$host} " . $reason . "\n";
}
}
}