I've written a function for easier database connections with the ability to connect via PDO or MySQLi options.
Currently I struggle with PHPDov @return
property.
I've reached the correct highlights of PDO methods in PhpStorm but I don't know how to make work similarly for both options. The code below may explain it better.
Here's my dbCon.php function:
<?php
# defining the root directory as constant
define('__ROOT__', dirname($_SERVER['DOCUMENT_ROOT']));
/**
* @param $db
* @param $conType
* @return PDO[]
*/
function dbCon($db, $conType)
{
# parse the data from db.ini where $db is database name
$_con = parse_ini_file(__ROOT__ . '/db.ini');
# set prefix if required by hosting to have one
$pre = 'database_';
# list parameters via variables
$_host = $_con[$db . '_ht'];
$_user = $pre . $_con[$db . '_un'];
$_database = $pre . $_con[$db . '_db'];
$_password = $_con[$db . '_pw'];
# PDO attributes
$_pdo_attr = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ERRMODE_WARNING // development mode only
];
# define dbCon variable;
$_dbCon = false;
# set PDO or MYSQLI connection
switch ($conType) {
case 'pdo':
try {
${$db . '_pdo'} = new PDO ("mysql:host=$_host;dbname=$_database; charset=utf8", $_user, $_password, $_pdo_attr);
$_dbCon = ${$db . '_pdo'};
$_dbSts = ${$db . '_pdo'}->getAttribute(PDO::ATTR_CONNECTION_STATUS);
} catch (PDOException $e) {
$_dbSts = false;
}
break;
case 'mysqli':
${$db . '_mysqli'} = new mysqli($_host, $_user, $_password, $_database);
if (${$db . '_mysqli'}->connect_error) $_dbSts = false;
else $_dbSts = explode(' ', mysqli_stat(${$db . '_mysqli'})); $_dbCon = ${$db . '_mysqli'};
break;
default:
$_dbSts = false; // error case
break;
}
# output
return ["dbSts" => $_dbSts,
"dbCon" => $_dbCon];
}
So, as you can see by..
/**
* @param $db
* @param $conType
* @return PDO[]
*/
..this works well for returning the PDO array but as the function allow to switch to MySQLi I'd like those methods to be highlighted as well.
If you want your function to return more than one type just put a pipe between them. I don't know what the specific return type of mysqli is but you're going to want something like this
@return PDO[]|MySQLi