0
I started to take a look at PDO and DAO but still do not understand how to do right.
I had some problems with the function bindParam that does not pass get method then I had to do a gambit.
And also how to handle the connection. I must pass the connection object in PDO?
What’s the right way to do it?
Follow the connection code, class, classeDAO and main (config_banco.php is where I save the connection data)
connect PDO.php:
include_once $_SERVER['DOCUMENT_ROOT']."/config.php";
include DIR_MODEL."config_banco.php";
function conectar (){
$cfg = new ConfigBanco();
try{
$db = new PDO("{$cfg->nomeSGBD}:host={$cfg->enderecoHost};dbname={$cfg->nomeBanco}",
$cfg->usuarioBanco,$cfg->senhaBanco);
return $db;
}
catch(PDOException $e){
echo $e->getLine() ." ". $e->getMessage().$cfg->usuarioBanco;
exit();
}
}
Php user.:
<?php
include_once $_SERVER['DOCUMENT_ROOT']."/config.php";
class Usuario{
private $login;
private $senha;
private$nome;
...
//Tenho aqui o construtor,os métodos get e set.
}
?>
User.php:
<?php
include_once $_SERVER['DOCUMENT_ROOT']."/config.php";
include_once DIR_MODEL."conectarPDO.php";
include_once DIR_MODEL."usuario.class.php";
class UsuarioDAO extends Usuario implements interfaceDAO {
public $pdo;
public function __construct($pdo){
$this->pdo = $pdo;
}
public function getPdo(){
return $this->pdo;
}
public function inserir($usuario) {
global $pdo;
$sql = "INSERT INTO `usuario`
(`login`, `senha`, `nome`)
VALUES (?,?,?)";
$result = $pdo -> prepare($sql);
//bindParam não aceita método get
$login = $usuario->getLogin();
$senha = $usuario->getSenha();
$nome = $usuario->getNome();
$result->bindParam(1, $login);
$result->bindParam(2, $senha);
$result->bindParam(3, $nome);
$result->execute();
}
}
?>
And a main just to test:
<?php
$usuario = new Usuario("login","nome,"senha");
$pdo = conectar();
$usuarioDAO = new UsuarioDAO($pdo);
$usuarioDAO->inserir($usuario);
?>
Thanks for the help.
It’s all right, about the
bindParam()
see What is the difference between bindParam and bindValue?– rray
Thanks! So it’s more business to use
bindValue()
. Is this the idea of spending $Pdo in the constructor? Is the connection going from class to class? If I had a class containing the business rule o$pdo
would be a constructor parameter?– Anth