marzz marzz - 2 months ago 17
PHP Question

OOP interactions between 2 files

I got a problem with interactions between 2 files. Im learning OOP on PHP but there's some things that i still not understand the operation. The error is Notice: Undefined variable: db in C:\wamp64\www\projet\connectDB.class.php on line 16 and Fatal error: Call to a member function prepare() on null in C:\wamp64\www\projet\connectDB.class.php on line 16

index.html:

<?php

require_once('connectDB.class.php');

try
{
$conn = new Connection('xe','copie_tdf','copie_tdf');
}catch (PDOException $err){
echo "Err " . $err->getMessage();
}

$sql="SELECT nom,prenom FROM tdf_coureur";
$result=$conn->selectdb($sql);
foreach ($result as $r)
{
echo $r->NOM." ".$r->PRENOM."<br/>";
}
?>


connectDB.class.php:

<?php
class Connection extends PDO{

protected $db;

public function __construct($dbname, $dbuser, $dbpass, $dbtype = 'oci')
{
$db = new PDO($dbtype.':dbname='.$dbname, $dbuser, $dbpass);
}


public function selectdb($querySelect)
{
$db->beginTransaction();
$select = $db->prepare($querySelect);
$select->execute();
$resultat=$select->fetchAll(PDO::FETCH_OBJ);

return $resultat;
}
}

?>


I hope you'll find a solution because I dont see any solution with my current knowledge. Thx beforehand

Answer

as mentioned in the comments

protected $db;

public function __construct($dbname, $dbuser, $dbpass, $dbtype = 'oci')
{
  $this->db = new PDO($dbtype.':dbname='.$dbname, $dbuser, $dbpass);
}

$this: refers to the instance of the class

Comments