Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Primeiramente, feliz natal.
Vamos a duvida.
Qual é o melhor dos 2 métodos que eu uso para cadastrar uma conta no banco
PHP Orientado a Objetos PDO
Método que uso, Repara que nele, eu coloco os métodos da classe direto na query,
outra diferença é o tamanho da função também, ela é mais compacta.
public function inserir_usuario($usuario){
try {
if ($this->verificaUsuario($usuario) == TRUE){
return $erro = "Usuário ou Email já cadastrados.";
}else if($this->verificaUsuario($usuario) == FALSE){
$this->Create = $this->Conn->prepare("INSERT INTO users(username,password,mail,auth_ticket,rank,credits,activity_points,look,gender,motto,account_created,ip_last,ip_reg,vip,real_name) VALUES('{$usuario->get_username()}','{$usuario->get_password()}','{$usuario->get_mail()}','{$usuario->get_auth_ticket()}','{$usuario->get_rank()}','{$usuario->get_credits()}','{$usuario->get_activity_points()}','{$usuario->get_look()}','{$usuario->get_gender()}','{$usuario->get_motto()}','{$usuario->get_account_created()}','{$usuario->get_ip_last()}','{$usuario->get_ip_reg()}','{$usuario->get_vip()}','{$usuario->get_real_name()}')");
$this->Create->execute();
if($this->Create->rowCount() > 0){
$this->Result = $this->Conn->LastInsertId();
return TRUE;
}else{
return FALSE;
}
}
} catch (PDOException $ex) {
exibeMensagens($Msg, $ErrNo);
}
}
Segundo método, neste eu uso o bindParam, e não coloco os métodos do objetos direto na query.
repare que o tamanho é bem maior, em relação a quantidade de linhas, lembrando que tive que declarar as variáveis com o Get da classe, pois ela direto no bindParam não funcionou.
public function inserir_usuario($usuario){
try {
if($this->verificaUsuario($usuario) == TRUE){
return $erro = "Usuário ou Email já cadastrados.";
}else if($this->verificaUsuario($usuario) == FALSE){
$nome = $usuario->get_username();
$senha = $usuario->get_password();
$email = $usuario->get_mail();
$tiket = $usuario->get_auth_ticket();
$rank = $usuario->get_rank();
$creditos = $usuario->get_credits();
$dukets = $usuario->get_activity_points();
$look = $usuario->get_look();
$sexo = $usuario->get_gender();
$missao = $usuario->get_motto();
$datacri = $usuario->get_account_created();
$ultimo_ip = $usuario->get_ip_last();
$ip_registro = $usuario->get_ip_reg();
$get_vip = $usuario->get_vip();
$nome_real = $usuario->get_real_name();
$query = "INSERT INTO users(username,password,mail,auth_ticket,rank,credits,activity_points,look,gender,motto,account_created,ip_last,ip_reg,vip,real_name) VALUES(:nome,:senha,:email,:tiket,:rank,:creditos,:dukets,:look,:sexo,:missao,:datacri,:ultimo_ip,:ip_registro,:get_vip,:nome_real";
$this->Create = $this->Conn->prepare($query);
$this->Create->bindParam(':nome' , $nome , PDO::PARAM_STR);
$this->Create->bindParam(':senha' , $senha , PDO::PARAM_STR);
$this->Create->bindParam(':email' , $email , PDO::PARAM_STR);
$this->Create->bindParam(':tiket' , $tiket , PDO::PARAM_STR);
$this->Create->bindParam(':rank' , $rank , PDO::PARAM_INT);
$this->Create->bindParam(':creditos' , $creditos , PDO::PARAM_INT);
$this->Create->bindParam(':dukets' , $dukets , PDO::PARAM_INT);
$this->Create->bindParam(':look' , $look , PDO::PARAM_STR);
$this->Create->bindParam(':sexo' , $sexo , PDO::PARAM_STR);
$this->Create->bindParam(':missao' , $missao , PDO::PARAM_STR);
$this->Create->bindParam(':datacri' , $datacri , PDO::PARAM_STR);
$this->Create->bindParam(':ultimo_ip' , $ultimo_ip , PDO::PARAM_STR);
$this->Create->bindParam(':ip_registro' , $ip_registro, PDO::PARAM_STR);
$this->Create->bindParam(':get_vip' , $get_vip , PDO::PARAM_INT);
$this->Create->bindParam(':nome_real' , $nome_real , PDO::PARAM_STR);
$this->Create->execute();
if($this->Create->rowCount() > 0){
$this->Result = $this->Conn->LastInsertId();
return TRUE;
}else{
return FALSE;
}
}
} catch (PDOException $ex) {
exibeMensagens("Erro ao consultar. {$ex->getMessage()}", WS_ERROR);
}
}
Qual deles é o mais indicado, e em relação a segurança de entrada de dados, o segundo é realmente melhor, ou não faz muita diferença?
Olá williams, quando eu na segunda função passo os get do objeto nos binds ele retorna o seguinte warning
Apenas variáveis devem ser passados por referência em C: \ xampp \ htdocs \ class \ UsuarioPdo.class.php na linha 42
tirando isso cadastra normalmente. mas exibe na tela, até sei que da para tirar, mas se ta mostrando algo deve está errado, aqui a função do jeito que vo^cê me indicou, eu ja havia feito assim antes.
mudei por conta do warning
Edição(2:54 AM Brasilia)
a função ficou desta forma agora, repare que alterei para bindValue();
public function inserir_usuario($usuario){
try {
if($this->verificaUsuario($usuario) == TRUE){
return $erro = "Usuário ou Email já cadastrados.";
}else if($this->verificaUsuario($usuario) == FALSE){
$query = "INSERT INTO users(username,password,mail,auth_ticket,rank,credits,activity_points,look,gender,motto,account_created,ip_last,ip_reg,vip,real_name) VALUES(:nome,:senha,:email,:tiket,:rank,:creditos,:dukets,:look,:sexo,:missao,:datacri,:ultimo_ip,:ip_registro,:get_vip,:nome_real)";
$this->Create = $this->Conn->prepare($query);
$this->Create->bindValue(':nome' , $usuario->get_username() , PDO::PARAM_STR);
$this->Create->bindValue(':senha' , $usuario->get_password() , PDO::PARAM_STR);
$this->Create->bindValue(':email' , $usuario->get_mail() , PDO::PARAM_STR);
$this->Create->bindValue(':tiket' , $usuario->get_auth_ticket() , PDO::PARAM_STR);
$this->Create->bindValue(':rank' , $usuario->get_rank() , PDO::PARAM_INT);
$this->Create->bindValue(':creditos' , $usuario->get_credits() , PDO::PARAM_INT);
$this->Create->bindValue(':dukets' , $usuario->get_activity_points() , PDO::PARAM_INT);
$this->Create->bindValue(':look' , $usuario->get_look() , PDO::PARAM_STR);
$this->Create->bindValue(':sexo' , $usuario->get_gender() , PDO::PARAM_STR);
$this->Create->bindValue(':missao' , $usuario->get_motto() , PDO::PARAM_STR);
$this->Create->bindValue(':datacri' , $usuario->get_account_created() , PDO::PARAM_STR);
$this->Create->bindValue(':ultimo_ip' , $usuario->get_ip_last() , PDO::PARAM_STR);
$this->Create->bindValue(':ip_registro' , $usuario->get_ip_reg() , PDO::PARAM_STR);
$this->Create->bindValue(':get_vip' , $usuario->get_vip() , PDO::PARAM_INT);
$this->Create->bindValue(':nome_real' , $usuario->get_real_name() , PDO::PARAM_STR);
$this->Create->execute();
if($this->Create->rowCount() == 1){
//$this->Result = $this->Conn->LastInsertId();
return TRUE;
}else{
return FALSE;
}
}
} catch (PDOException $ex) {
exibeMensagens("Erro ao consultar. {$ex->getMessage()}", WS_ERROR);
}
}
Como julgaria esta função numa escala, ruim, intermediário, ótimo
Wiliams, não aguentei e fui dar uma olhada no manual do php, como pode ver, la mesmo diz que vai gerar um Warning, caso esteja habilitado para tal, o modo de resolver, seria fazer uma variavel real receber o metodo, assim como estava no primeiro codigo que mandei, ou altear para bindValue, como não sei a diferença ainda, vou dar mais uma pesquisada, mas até o momento vou deixar aberto o tópico!
trecho do manual do php
http://php.net/manual/pt_BR/pdostatement.bindparam.php
Mike Robinson ¶3 anos atrás
Note that with bindParam the second parameter is passed by reference. This means that the following will produce a warning if E_STRICT is enabled:
<?php
$stmt->bindParam('type', $object->getType());
// Strict Standards: Only variables should be passed by reference in /path/to/file.php on line 123
?>
If the second parameter is not an actual variable, either set the result of $object->getType(); to a variable and use that variable in bindParam or use bindValue instead.
public function inserir_usuario($usuario){
try {
if($this->verificaUsuario($usuario) == TRUE){
return $erro = "Usuário ou Email já cadastrados.";
}else if($this->verificaUsuario($usuario) == FALSE){
$query = "INSERT INTO users(username,password,mail,auth_ticket,rank,credits,activity_points,look,gender,motto,account_created,ip_last,ip_reg,vip,real_name) VALUES(:nome,:senha,:email,:tiket,:rank,:creditos,:dukets,:look,:sexo,:missao,:datacri,:ultimo_ip,:ip_registro,:get_vip,:nome_real)";
$this->Create = $this->Conn->prepare($query);
$this->Create->bindParam(':nome' , $usuario->get_username() , PDO::PARAM_STR);
$this->Create->bindParam(':senha' , $usuario->get_password() , PDO::PARAM_STR);
$this->Create->bindParam(':email' , $usuario->get_mail() , PDO::PARAM_STR);
$this->Create->bindParam(':tiket' , $usuario->get_auth_ticket() , PDO::PARAM_STR);
$this->Create->bindParam(':rank' , $usuario->get_rank() , PDO::PARAM_INT);
$this->Create->bindParam(':creditos' , $usuario->get_credits() , PDO::PARAM_INT);
$this->Create->bindParam(':dukets' , $usuario->get_activity_points() , PDO::PARAM_INT);
$this->Create->bindParam(':look' , $usuario->get_look() , PDO::PARAM_STR);
$this->Create->bindParam(':sexo' , $usuario->get_gender() , PDO::PARAM_STR);
$this->Create->bindParam(':missao' , $usuario->get_motto() , PDO::PARAM_STR);
$this->Create->bindParam(':datacri' , $usuario->get_account_created() , PDO::PARAM_STR);
$this->Create->bindParam(':ultimo_ip' , $usuario->get_ip_last() , PDO::PARAM_STR);
$this->Create->bindParam(':ip_registro' , $usuario->get_ip_reg() , PDO::PARAM_STR);
$this->Create->bindParam(':get_vip' , $usuario->get_vip() , PDO::PARAM_INT);
$this->Create->bindParam(':nome_real' , $usuario->get_real_name() , PDO::PARAM_STR);
$this->Create->execute();
if($this->Create->rowCount() == 1){
//$this->Result = $this->Conn->LastInsertId();
return TRUE;
}else{
return FALSE;
}
}
} catch (PDOException $ex) {
exibeMensagens("Erro ao consultar. {$ex->getMessage()}", WS_ERROR);
}
}Se ta falando para passar a Referencia do Objeto, passe a Referencia do Objeto que é o nome da classe de onde vem os Geterrs e Setters uai, isso se chama encapsulamento. A primeira coisa quando se estuda OOP.
Se o nome da Classe for Usuario passe ela, senão for, use a nomenclatura que colocou.
Exemplo;
public function inserir_usuario(Usuario $usuario) {
...
}
Na escala: BÁSICOjá esta passando o objeto, como pode ver o parametro da função é só 1, no caso usuario, e sempr eque chamo os gets tem a referencia da class, o encapsulamento $usuario->get_..... o problema é que não se usa bindParam com funções, se usa com variaveis reais, ou constantes, assim se diz no manual do PHP
public function inserir_usuario($usuario){
try {
if($this->verificaUsuario($usuario) == TRUE){
return $erro = "Usuário ou Email já cadastrados.";
}else if($this->verificaUsuario($usuario) == FALSE){
$query = "INSERT INTO users(username,password,mail,auth_ticket,rank,credits,activity_points,look,gender,motto,account_created,ip_last,ip_reg,vip,real_name) VALUES(:nome,:senha,:email,:tiket,:rank,:creditos,:dukets,:look,:sexo,:missao,:datacri,:ultimo_ip,:ip_registro,:get_vip,:nome_real)";
$this->Create = $this->Conn->prepare($query);
$this->Create->bindValue(':nome' , $usuario->get_username() , PDO::PARAM_STR);
$this->Create->bindValue(':senha' , $usuario->get_password() , PDO::PARAM_STR);
$this->Create->bindValue(':email' , $usuario->get_mail() , PDO::PARAM_STR);
$this->Create->bindValue(':tiket' , $usuario->get_auth_ticket() , PDO::PARAM_STR);
$this->Create->bindValue(':rank' , $usuario->get_rank() , PDO::PARAM_INT);
$this->Create->bindValue(':creditos' , $usuario->get_credits() , PDO::PARAM_INT);
$this->Create->bindValue(':dukets' , $usuario->get_activity_points() , PDO::PARAM_INT);
$this->Create->bindValue(':look' , $usuario->get_look() , PDO::PARAM_STR);
$this->Create->bindValue(':sexo' , $usuario->get_gender() , PDO::PARAM_STR);
$this->Create->bindValue(':missao' , $usuario->get_motto() , PDO::PARAM_STR);
$this->Create->bindValue(':datacri' , $usuario->get_account_created() , PDO::PARAM_STR);
$this->Create->bindValue(':ultimo_ip' , $usuario->get_ip_last() , PDO::PARAM_STR);
$this->Create->bindValue(':ip_registro' , $usuario->get_ip_reg() , PDO::PARAM_STR);
$this->Create->bindValue(':get_vip' , $usuario->get_vip() , PDO::PARAM_INT);
$this->Create->bindValue(':nome_real' , $usuario->get_real_name() , PDO::PARAM_STR);
$this->Create->execute();
if($this->Create->rowCount() == 1){
//$this->Result = $this->Conn->LastInsertId();
return TRUE;
}else{
return FALSE;
}
}
} catch (PDOException $ex) {
exibeMensagens("Erro ao consultar. {$ex->getMessage()}", WS_ERROR);
}
}
esta seria a forma correta!
mto obrigado.
>
o problema é que não se usa bindParam com funções, se usa com variaveis reais, ou constantes, assim se diz no manual do PHP
esta seria a forma correta!
mto obrigado.
Meu Jesus, Não fale m***** senão sabe, tenha ciência em uma coisa, você ta aprendendo, e falar que não sei como se usa funções é o fim, BindParam é uma função da Classe PDOStatement e é como se fosse a caca acima que você esta fazendo, que também usa funções e que espera parâmetros.
A bindParam espera os seguinte Argumentos
/**
* (PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)<br/>
* Binds a parameter to the specified variable name
* @link http://php.net/manual/en/pdostatement.bindparam.php
* @param mixed $parameter <p>
* Parameter identifier. For a prepared statement using named
* placeholders, this will be a parameter name of the form
* :name. For a prepared statement using
* question mark placeholders, this will be the 1-indexed position of
* the parameter.
* </p>
* @param mixed $variable <p>
* Name of the PHP variable to bind to the SQL statement parameter.
* </p>
* @param int $data_type [optional] <p>
* Explicit data type for the parameter using the PDO::PARAM_*
* constants.
* To return an INOUT parameter from a stored procedure,
* use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT bits
* for the <i>data_type</i> parameter.
* </p>
* @param int $length [optional] <p>
* Length of the data type. To indicate that a parameter is an OUT
* parameter from a stored procedure, you must explicitly set the
* length.
* </p>
* @param mixed $driver_options [optional] <p>
* </p>
* @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure.
*/
public function bindParam ($parameter, &$variable, $data_type = PDO::PARAM_STR, $length = null, $driver_options = null) {}
Ou seja http://php.net/manual/pt_BR/pdostatement.bindparam.php
&$variable
o segundo parâmetro é uma variável referenciada, não interessa de como ela vem, tem que passar a referencia se quiser usar.
http://php.net/manual/pt_BR/language.references.pass.php
Se trocou por bindValue otimo, melhor ainda.
...................
Pra falar a verdade eu pego leve, se fosse outro ia falar pra você, o que você ta fazendo, teria que jogar no lixo e refazer do zero.
Já começaria por aqui
Que m***** é essa, a mesma consulta 2x
if($this->verificaUsuario($usuario) == TRUE){
return $erro = "Usuário ou Email já cadastrados.";
}else if($this->verificaUsuario($usuario) == FALSE){
Esses Getters com _ get_username, use a nomenclatura correta $this->getUsername(), se esta referenciando $usuario->getUsername(), falta de onde vem, já falei acima, senão sabe usar então fica difícil.
Mas com você nem perco mais tempo, você já sabe.
>
Meu Jesus, Não fale m***** senão sabe, tenha ciência em uma coisa, você ta aprendendo, e falar que não sei como se usa funções é o fim, BindParam é uma função da Classe PDOStatement e é como se fosse a caca acima que você esta fazendo, que também usa funções e que espera parâmetros.
A bindParam espera os seguinte Argumentos
/**
* (PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)<br/>
* Binds a parameter to the specified variable name
* @link http://php.net/manual/en/pdostatement.bindparam.php
* @param mixed $parameter <p>
* Parameter identifier. For a prepared statement using named
* placeholders, this will be a parameter name of the form
* :name. For a prepared statement using
* question mark placeholders, this will be the 1-indexed position of
* the parameter.
* </p>
* @param mixed $variable <p>
* Name of the PHP variable to bind to the SQL statement parameter.
* </p>
* @param int $data_type [optional] <p>
* Explicit data type for the parameter using the PDO::PARAM_*
* constants.
* To return an INOUT parameter from a stored procedure,
* use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT bits
* for the <i>data_type</i> parameter.
* </p>
* @param int $length [optional] <p>
* Length of the data type. To indicate that a parameter is an OUT
* parameter from a stored procedure, you must explicitly set the
* length.
* </p>
* @param mixed $driver_options [optional] <p>
* </p>
* @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure.
*/
public function bindParam ($parameter, &$variable, $data_type = PDO::PARAM_STR, $length = null, $driver_options = null) {}
Ou seja http://php.net/manual/pt_BR/pdostatement.bindparam.php
&$variable
o segundo parâmetro é uma variável referenciada, não interessa de como ela vem, tem que passar a referencia se quiser usar.
http://php.net/manual/pt_BR/language.references.pass.php
Se trocou por bindValue otimo, melhor ainda.
...................
Pra falar a verdade eu pego leve, se fosse outro ia falar pra você, o que você ta fazendo, teria que jogar no lixo e refazer do zero.
Já começaria por aqui
Que m***** é essa, a mesma consulta 2x
if($this->verificaUsuario($usuario) == TRUE){
return $erro = "Usuário ou Email já cadastrados.";
}else if($this->verificaUsuario($usuario) == FALSE){
Esses Getters com _ get_username, use a nomenclatura correta $this->getUsername(), se esta referenciando $usuario->getUsername(), falta de onde vem, já falei acima, senão sabe usar então fica difícil.
Mas com você nem perco mais tempo, você já sabe.
poxa cara que isso? você ta aloprando porque? em momento algum eu falei que você não sabe, eu só falei que o erro era por conta do metodo no bind, jamais tentei te ofender nem desmerecer o teu conhecimento, eu apenas mencionei como resolvi o erro, e se resolvi foi por conta do seu primeiro comentario, indicando para usar de outra forma.
queria pedir a algum moderador do forum para deletar o tópico, fiquei bastante constrangido.
Quando você disse que não se usa, passou a impressão do que o que indiquei ta errado, que é passar o nome da Classe na interface inserir_usuario, que veio por meio de injeção, para usar no bind.
Aqui é um fórum, ninguém passa mão na cabeça de ninguém, se ficou constrangido fazer o que, tem que redigir boas respostas, para não dar um falso positivo como foi feito acima.
As duas tem que melhorar.
Na primeira da para usar a Parametrização da QUERY da Segunda, o que fica mais organizado.
Na segunda. qual a diferença em declarar as variáveis local para depois usar nos binds?
Não pode usar diretamente?
$this->Create->bindParam(':nome' , $usuario->get_username(), PDO::PARAM_STR);
Porque não retorna logo o ID?
Abaixo, retorna logo um false ou declare uma Exception