<?php
header("Content-Type: text/html;charset=utf-8");
error_reporting(E_ALL | E_STRICT);
$param_arr = getopt('h:u:p:d:');
$host = $param_arr['h'] ?: '127.0.0.1';
$user = $param_arr['u'];
$pwd = $param_arr['p'];
$dbname = $param_arr['d'];
// 判断数据库是否存在
try {
$conn = new PDO("mysql:host=$host", $user, $pwd);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "show databases;";
// 使用 exec() ,因为没有结果返回
$res = $conn->query($sql);
$res = $res->fetchAll(PDO::FETCH_ASSOC);
$database_list = [];
foreach($res as $k => $v) {
$database_list[] = $v['Database'];
}
if (in_array($dbname,$database_list)) {
echo 1; // 存在
} else {
echo 2; // 不存在
}
$conn = null;
return;
} catch (PDOException $e) {
// echo $sql . "<br>" . $e->getMessage();
echo 0;
$conn = null;
return;
}