I do this using PDO:
/** @var PDO */
private static $connect = null;
/**
* Conecta com o banco de dados com o pattern singleton
* Retorna um objeto PDO!
*/
private static function Conectar(){
try {
Setup::checkLocal();
if(self::$connect == null) {
$dsn = 'mysql:host='.Setup::$host.';dbname='.Setup::$base;
$options = [ PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8" ];
self::$connect = new PDO($dsn, Setup::$user, Setup::$pass, $options);
}
} catch (PDOException $e) {
echo 'PDOException: erro ao conectar ao banco de dados.';
//PHPErro($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
die;
}
self::$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//self::$connect->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);
return self::$connect;
}
/** Retorna um objeto PDO Singleton Pattern */
public static function getConn(){
return self::Conectar();
}
public static function prepareQuery($query, $params){
$preparedQuery = self::getConn()->prepare($query);
foreach ($params as $key => $value) {
$preparedQuery->bindValue($key, $value);
}
$preparedQuery->execute();
$result = $preparedQuery->fetchAll(PDO::FETCH_OBJ);
self::$connect = null;
return $result;
}
And I usually access this way:
$qrSelect = "SELECT campo1, campo2 FROM tabela WHERE campo1 = :campo1 ORDER BY campo1 ASC";
$params = [":campo1" => $valor];
$retorno = Conexao::prepareQuery($qrSelect, $params);
I always pass the entire query. What always changes are the parameters. I do not see much gain in saving the words select
and from
when calling the method select
, if to compensate you will have to pass several parameters and make other validations.