Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Boas ppl fiz esta class à um tempo vou postar aqui para saber as vossas opiniões sobre ela e o que deve melhor nela, e se existirem bugs para reportarem
Funcionalidades:
Cumprimentos
Ficheiro class.Basedados.php
<?php
/**
* @author LaBoss
*
*
*/
class BaseDados extends mysqli {
function __construct() {
$hostname = DB_SERVIDOR;
$username = DB_USER;
$password = DB_PASS;
$database = DB_NOME;
$porta = DB_PORTA;
@parent::__construct ( $hostname, $username, $password, $database, $porta );
if ($this->connect_errno == 1045) {
throw new RuntimeException ( 'Acesso Negado à base dados' );
} elseif ($this->connect_errno == 1049) {
throw new RuntimeException ( 'Erro ao selecionar a Base de Dados' );
} elseif ($this->connect_errno == 2002) {
throw new RuntimeException ( 'Servidor SQL Desconhecido' );
} elseif ($this->connect_errno != 0) {
throw new RuntimeException ( $this->connect_errno . $this->connect_error );
}
}
private function CarregarParametros($arr) {
$refs = array ();
foreach ( $arr as $key => $value ) {
$refs [$key] = &$arr [$key];
}
return $refs;
}
public function MontarWhere($Campos) {
$SQLFiltro = "";
for($i = 0; $i <= count ( $Campos ) - 1; $i ++) {
if ($i == 0) {
$SQLFiltro = " WHERE " . $Campos [$i];
} else {
$SQLFiltro .= " AND " . $Campos [$i];
}
}
return $SQLFiltro;
}
public function MontarOrder($Dados) {
$SQLOrdem = "";
if ($Dados ["Campos"] [0] == "RAND") {
return " ORDER BY RAND()";
} else {
for($i = 0; $i <= count ( $Dados ["Campos"] ) - 1; $i ++) {
if ($i == 0) {
$SQLFiltro = " ORDER BY " . $Dados ["Campos"] [$i];
} else {
$SQLFiltro .= "," . $Dados ["Campos"] [$i];
}
}
return $SQLFiltro . " " . $Dados ["Ordem"];
}
}
private function Paginacao($DadosPaginacao, $Query, $Parametros = array()) {
$PaginaActual = empty ( $DadosPaginacao ["Actual"] ) ? 1 : ( int ) $DadosPaginacao ["Actual"];
$Itens_PorPagina = empty ( $DadosPaginacao ["ItensPagina"] ) ? 15 : ( int ) $DadosPaginacao ["ItensPagina"];
$PrimeiroRegisto = (($PaginaActual * $Itens_PorPagina) <= 0) ? 0 : ($PaginaActual * $Itens_PorPagina) - $Itens_PorPagina;
$QueryTotal = preg_replace ( array ('/SELECT(.*)FROM /Asi', '/ORDER BY (.*)/i' ), array ('SELECT COUNT(*) AS Total FROM ', '' ), $Query, 1 );
$TotalDados = self::Query ( $QueryTotal, array (), array (), $Parametros );
$TotalRegistos = $TotalDados ["Dados"][0] ["Total"];
$N_Total_Paginas = ceil ( $TotalRegistos / $Itens_PorPagina ); // Diz quantas paginas vai gerar
$PaginaSeguinte = ($PaginaActual < $N_Total_Paginas) ? $PaginaActual + 1 : NULL;
$PaginaAnterior = ($PaginaActual > 1 && $PaginaActual <= $N_Total_Paginas) ? $PaginaActual - 1 : NULL;
return array ("SQLLimit" => "LIMIT {$PrimeiroRegisto}, {$Itens_PorPagina}", "InfosPaginacao" => array ("TotalRegistos" => $TotalRegistos, "ItensPorPagina" => $Itens_PorPagina, "TotalPaginas" => $N_Total_Paginas, "PaginaActual" => $PaginaActual, "PaginaAnterior" => $PaginaAnterior, "PaginaSeguinte" => $PaginaSeguinte, "PrimeiraPagina" => 1, "UltimaPagina" => $N_Total_Paginas ) );
}
public function Query($Query, $Where = array(), $Ordem = array(), $Parametros = array(), $Paginacao = array()) {
$Colunas = array ();
$Resultados = array ();
$Linha = array ();
$PaginacaoDados = array ();
$WhereSQL = (count ( $Where )) ? self::MontarWhere ( $Where ) : "";
$OrdemSQL = (count ( $Ordem )) ? self::MontarOrder ( $Ordem ) : "";
$QueryFinal = $Query . $WhereSQL . $OrdemSQL;
/*
* Paginacao
*/
if (count ( $Paginacao ) > 0) {
$PaginacaoDados = self::Paginacao ( $Paginacao, $QueryFinal, $Parametros );
$QueryFinal = $QueryFinal . " " . $PaginacaoDados ["SQLLimit"];
}
$stmt = parent::prepare ( $QueryFinal );
if ($stmt) {
/*
* Carrega os Parametros :P
*/
if (count ( $Parametros ) > 0) {
call_user_func_array ( array ($stmt, 'bind_param' ), self::CarregarParametros ( $Parametros ) );
}
$stmt->execute ();
$stmt->store_result ();
/*
* Carrega todos os campos no Select
*/
$meta = $stmt->result_metadata ();
while ( ($Campo = $meta->fetch_field ()) != false ) {
$Colunas [] = &$Linha [$Campo->name];
}
call_user_func_array ( array ($stmt, 'bind_result' ), $Colunas );
/*
* Carrega todos os Dados
*/
while ( $stmt->fetch () ) {
$x = array ();
foreach ( $Linha as $key => $val ) {
$x [$key] = $val;
}
$Resultados [] = $x;
}
$Dados = array ("Dados" => $Resultados);
$Infos = array ("InfosSQL" => array ("num_rows" => $stmt->num_rows, "affected_rows" => $stmt->affected_rows, "field_count" => $stmt->field_count, "sqlstate" => $stmt->sqlstate ) );
$ArrPaginas = (count ( $PaginacaoDados ) > 0) ? array ("Paginacao" => $PaginacaoDados ["InfosPaginacao"] ) : array ();
return array_merge ( $Dados, $ArrPaginas, $Infos );
} else {
throw new RuntimeException ( self::Erro () );
}
}
public function Operacoes($Query, $Parametros = array()) {
$Colunas = array ();
$Resultados = array ();
$Linha = array ();
$stmt = parent::prepare ( $Query );
if ($stmt) {
/*
* Carrega os Parametros :P
*/
if (count ( $Parametros ) > 0) {
call_user_func_array ( array ($stmt, 'bind_param' ), self::CarregarParametros ( $Parametros ) );
}
$stmt->execute ();
$stmt->store_result ();
$Infos = array ("InfosSQL" => array ("ID_Inserido" => $stmt->insert_id, "num_rows" => $stmt->num_rows, "affected_rows" => $stmt->affected_rows, "field_count" => $stmt->field_count, "sqlstate" => $stmt->sqlstate ) );
return $Infos;
} else {
throw new RuntimeException ( self::Erro () );
}
}
public function Erro() {
if ($this->errno || $this->error) {
return sprintf ( "Erro (%d): %s", $this->errno, $this->error );
}
}
function __destruct() {
parent::close ();
}
}
?>
Ficheiro Demo.php
<?php
define("DB_SERVIDOR", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NOME", "testes");
define("BD_PREF", "");
define("DB_PORTA", 3306);
include "class.Basedados.php";
try {
$BD = new BaseDados ();
echo "<pre>";
print_r ( $BD->Operacoes ( "UPDATE utilizadores SET U_Login = ? WHERE U_ID = ?", array ("si", "DanielCris", 2 ) ) );
print_r ( $Inserido = $BD->Operacoes ( "INSERT INTO utilizadores (U_Login) VALUES (?);", array ("s", "DanielCris" ) ) );
print_r ( $BD->Query ( "SELECT * FROM utilizadores " ) );
print_r ( $Inserido = $BD->Operacoes ( "DELETE FROM utilizadores WHERE U_ID = ?", array ("i", $Inserido ["InfosSQL"] ["ID_Inserido"] ) ) );
$Where = array("U_ID BETWEEN ? AND ?");
$Order = array("Campos" => array("U_ID"), "Ordem" => "ASC");
$Parametros = array("ii", 2, 9);
$Paginacao = array("ItensPagina" => 2, "Actual" => $_GET["p"]);
print_r (
$BD->Query ( "SELECT * FROM utilizadores ",
$Where,
$Order,
$Parametros,
$Paginacao)
);
} catch ( Exception $e ) {
echo $e->getMessage (), "\n";
}Carregando comentários...