function database_connection_with_pdo($host, $database, $user, $password, $port=3306, $charset='utf8mb4') {
try {
$dns = "mysql:host=$host;";
if ($port) {
$dns .= "port=$port;";
}
$dns .= "dbname=$database";
if ($charset) {
$dns .= ";charset=$charset";
}
$pdo = new PDO($dns, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 设置错误模式为异常
} catch (PDOException $e) {
throw new PDOException($e->getMessage(), (int)$e->getCode());
}
return $pdo;
}
用法:$conn = database_connection_with_pdo($MySQLServer, $MySQLDBName, $MySQLUserName, $MySQLPassword, $MySQLPort, $charset='utf8mb4');