Commit inicial
This commit is contained in:
63
include/bd_pdo.php
Normal file
63
include/bd_pdo.php
Normal file
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
require_once ($ruta ?? "./") . "vendor/autoload.php";
|
||||
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
|
||||
$dotenv->load();
|
||||
use \SeinopSys\PostgresDb;
|
||||
|
||||
# Connect to the database
|
||||
try {
|
||||
// Postgres
|
||||
$pdo = new PDO("pgsql:host=" . $_ENV['DB_HOST'] . ";dbname=" . $_ENV['DB_NAME'], $_ENV['DB_USER'], $_ENV['DB_PASS']);
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
$db = new PostgresDb();
|
||||
$db->setConnection($pdo);
|
||||
} catch (PDOException $e) {
|
||||
echo "Error: " . $e->getMessage();
|
||||
}
|
||||
|
||||
// check recursivelly if the array has only empty strings
|
||||
function is_response_empty($array)
|
||||
{
|
||||
foreach ($array as $value) {
|
||||
if (is_array($value)) {
|
||||
if (!is_response_empty($value)) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (!empty($value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// SQL function
|
||||
function query(string $sql, array $params = null, bool $single = true)
|
||||
{
|
||||
global $pdo;
|
||||
try {
|
||||
$stmt = $pdo->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
$response = $single ? $stmt->fetch(PDO::FETCH_ASSOC) : $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
return $response;
|
||||
} catch (PDOException $e) {
|
||||
echo "Error: " . $e->getMessage();
|
||||
return false;
|
||||
} finally {
|
||||
$stmt->closeCursor();
|
||||
$stmt = null;
|
||||
}
|
||||
}
|
||||
|
||||
function queryAll(string $sql, array $params = null)
|
||||
{
|
||||
return query($sql, $params, false);
|
||||
}
|
||||
|
||||
function toSQLArray(array $array): string
|
||||
{
|
||||
return sprintf("{%s}", implode(", ", $array));
|
||||
}
|
||||
Reference in New Issue
Block a user