0

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

marzz
  • 3
  • 1
  • The solition is using `$this`. – u_mulder Sep 27 '16 at 19:30
  • Use `$this->db` instead of `$db`. – Shira Sep 27 '16 at 19:30
  • ok thx @ShiraNai7 and u_mulder i'll check what $this refers to i dont understand this notion – marzz Sep 27 '16 at 19:34
  • @marzz `$this` refers to the current class _instance_. Just using `$db` refers to a _local_ variable that loses scope the moment execution leaves a function. `$this->db` is a _class property_ that remains in scope as long as the _object_ is being referenced – Jeff Lambert Sep 27 '16 at 19:49

1 Answers1

0

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

Vural
  • 8,666
  • 11
  • 40
  • 57
  • Ok, thank you all for your explanation I understand way better how it works now. Love you :* – marzz Sep 27 '16 at 19:57