Skip to content

Instantly share code, notes, and snippets.

@parzibyte

parzibyte/bd.php Secret

Created January 13, 2021 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/17b06acde5e3bde3356ea9898934add5 to your computer and use it in GitHub Desktop.
Save parzibyte/17b06acde5e3bde3356ea9898934add5 to your computer and use it in GitHub Desktop.
<?php
function obtenerVariableDelEntorno($key)
{
if (defined("_ENV_CACHE")) {
$vars = _ENV_CACHE;
} else {
$file = "env.php";
if (!file_exists($file)) {
throw new Exception("El archivo de las variables de entorno ($file) no existe. Favor de crearlo");
}
$vars = parse_ini_file($file);
define("_ENV_CACHE", $vars);
}
if (isset($vars[$key])) {
return $vars[$key];
} else {
throw new Exception("La clave especificada (" . $key . ") no existe en el archivo de las variables de entorno");
}
}
function obtenerConexion()
{
$password = obtenerVariableDelEntorno("MYSQL_PASSWORD");
$user = obtenerVariableDelEntorno("MYSQL_USER");
$dbName = obtenerVariableDelEntorno("MYSQL_DATABASE_NAME");
$database = new PDO('mysql:host=localhost;dbname=' . $dbName, $user, $password);
$database->query("set names utf8;");
$database->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$database->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
return $database;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment