Jump to content
Fórum Script Brasil
  • 0

Duvida


Guest Caio Canalli

Question

Guest Caio Canalli

Bom dia a todos! Tenho uma duvida simples em relaçao ao acesso do PHP ao banco de dados. Estou criando um aplicaçao de grande porte em que terei que fazer muitos acessos ao banco de dados, com diferentes classes( Cadastro, Alteracao). Qual a melhor maneira de fazer essas operaçoes: criando um arquivo separado com todos os tipos de consulta, inserçao, atualizaçao no banco de dados ou, ir fazendo esses acessos ao longo de todo o meu codigo? Por exemplo: tenho um arquivo chamdo UsuarioService com essas e outras funçoes

#################################################################################################################

public function getUsuarioByUser($itemID) {

$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename where usuario_user=?");

$this->throwExceptionOnError();

mysqli_stmt_bind_param($stmt, 's', $itemID);

$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);

$this->throwExceptionOnError();

mysqli_stmt_bind_result($stmt, $row->usuario_id, $row->usuario_user, $row->usuario_senha, $row->usuario_logado, $row->usuario_nivel, $row->Perfil_perfil_id);

if(mysqli_stmt_fetch($stmt)) {

return $row;

} else {

return null;

}

}

public function getUsuarioBySenha($itemUsuario, $itemSenha) {

$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename where usuario_user=? AND usuario_senha=?");

$this->throwExceptionOnError();

//$senha = md5($itemSenha);

mysqli_stmt_bind_param($stmt, 'ss', $itemUsuario, $itemSenha);

$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);

$this->throwExceptionOnError();

mysqli_stmt_bind_result($stmt, $row->usuario_id, $row->usuario_user, $row->usuario_senha, $row->usuario_logado, $row->usuario_nivel, $row->Perfil_perfil_id);

if(mysqli_stmt_fetch($stmt)) {

return $row;

} else {

return null;

}

}

#############################################################################################################################

Ou eu devo utilizar essa sintaxe:

#############################################################################################################################

class AgendaDAO extends PDOConnectionFactory {

// irá receber uma conexão

public $conex = null;

// constructor

public function AgendaDAO(){

$this->conex = PDOConnectionFactory::getConnection();

}

// realiza uma inserção

public function Insere( $agenda ){

try{

// preparo a query de inserçao - Prepare Statement

// note que no logar dos valores eu não estou passando ".$agenda->getValorx().", ...

// isso ficaria uma porta aberta para um SQL Injection.

$stmt = $this->conex->prepare("INSERT INTO agenda (id, nome, email, telefone) VALUES (?, ?, ?, ?)");

// valores encapsulados nas variáveis da classe Agenda.

// sequencia de índices que representa cada valor de minha query

$stmt->bindValue(1, $agenda->getId() );

$stmt->bindValue(2, $agenda->getNome() );

$stmt->bindValue(3, $agenda->getEmail() );

$stmt->bindValue(4, $agenda->getTelefone() );

// executo a query preparada

$stmt->execute();

// fecho a conexão

$this->conex = null;

// caso ocorra um erro, retorna o erro;

}catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); }

}

// realiza um Update

public function Update( $agenda, $condicao ){

try{

// preparo a query de update - Prepare Statement

$stmt = $this->conex->prepare("UPDATE agenda SET nome=?, email=?, telefone=? WHERE id=?");

$this->conex->beginTransaction();

// valores encapsulados nas variáveis da classe Agenda.

// sequencia de índices que representa cada valor de minha query

$stmt->bindValue(1, $agenda->getNome() );

$stmt->bindValue(2, $agenda->getEmail() );

$stmt->bindValue(3, $agenda->getTelefone() );

$stmt->bindValue(4, $condicao);

// executo a query preparada

$stmt->execute();

$this->conex->commit();

// fecho a conexão

$this->conex = null;

// caso ocorra um erro, retorna o erro;

}catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); }

}

// remove um registro

public function Deleta( $id ){

try{

// executo a query

$num = $this->conex->exec("DELETE FROM agenda WHERE id=$id");

// caso seja execuado ele retorna o número de rows que foram afetadas.

if( $num >= 1 ){ return $num; } else { return 0; }

// caso ocorra um erro, retorna o erro;

}catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); }

}

public function Lista($query=null){

try{

if( $query == null ){

// executo a query

$stmt = $this->conex->query("SELECT * FROM agenda");

}else{

$stmt = $this->conex->query($query);

}

// desconecta

$this->conex = null;

// retorna o resultado da query

return $stmt;

}catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); }

}

}

#############################################################################################################################

Obrigado pela ajuda!!!

Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Forum Statistics

    • Total Topics
      152.2k
    • Total Posts
      652k
×
×
  • Create New...