I started to take a look at PDO and DAO but I still did not understand how to do it right.
I had some problems with the bindParam function that does not let pass method get there had to do a gambiarra.
And also how to handle the connection. Should I pass the connection object on the PDO?
What's the right way to do it?
The following is the code for the connection, class, classAO and main (The config_banco.php is where I keep the connection data)
connect.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();
}
}
User.php:
<?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.
}
?>
Username.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.