How to access PDO prepare and execute from inside a class.
Posted: Mon Mar 30, 2009 3:40 am
[UPDATE]
I'm absolutly newbie on PHP and OOP :s
But I really want to learn, so any comments will be greatly appreciated. I'm trying to understand how things work...
[/UPDATE]
I have connected to the database, using my first class and with PDO. Good.
Working class:
I'd like to get data from the database using the prepare/execute methods.
I've tried this:
But I get an error: " Call to undefined method LigacaoBD::prepare() ..." and
it's correct, because the LigacaoBD doesn't have this method. The PDO has.
So, I though, instead of using this:
Maybe I can get this:
Change the scope of class property conexao to: public ;
And call it like this:
Ok. This seems to work BUT, I know that it's not a good OO policy to access
class properties directly (right?), so this is not a good method...
Question:
Can please someone explain to me, how can we PROPERLY access the PDO prepare
method from within an instantiated class, where that PDO resides?
How can I access the prepare PDO method, from an instance of the class
LigacaoBD ?
Thanks a lot,
Márcio
I'm absolutly newbie on PHP and OOP :s
But I really want to learn, so any comments will be greatly appreciated. I'm trying to understand how things work...
[/UPDATE]
I have connected to the database, using my first class and with PDO. Good.
Working class:
Code: Select all
class LigacaoBD
{
private $username;
private $password;
private $dsn; //a variável relativa ao data source name usado pelo
PHP Data Objects.
private $conexao;
public function __construct () {
$this->dsn =
"mysql:unix_socket=/tmp/mysql.sock;dbname=nome_da_base_de_dados";
$this->username = "username_bd";
$this->password = "password_bd";
}
public function efectuaLigacaoBD () {
try {
$this->conexao = new PDO($this->dsn,
$this->username, $this->password);
}
catch(PSOException $e){
echo "Erro de Conexão: " .$e->getMessage();
}
}
public function terminaLigacaoBD () {
$this->conexao = NULL;
}
}I've tried this:
Code: Select all
$handlerbd->prepare('SELECT * FROM users');it's correct, because the LigacaoBD doesn't have this method. The PDO has.
So, I though, instead of using this:
Code: Select all
$handlerbd->prepare('SELECT * FROM users');Change the scope of class property conexao to: public ;
And call it like this:
Code: Select all
$handlerdb->conexao->prepare('SELECT * FROM users');class properties directly (right?), so this is not a good method...
Question:
Can please someone explain to me, how can we PROPERLY access the PDO prepare
method from within an instantiated class, where that PDO resides?
How can I access the prepare PDO method, from an instance of the class
LigacaoBD ?
Thanks a lot,
Márcio