Hé les gars, j'ai un cours de connexion que j'ai trouvé pour pdo. J'appelle la méthode de connexion sur la page sur laquelle le fichier est inclus. Le problème est que dans les fonctions la variable $ conn n'est pas définie même si j'ai déclaré que la méthode était publique (nue avec moi je suis très nouveau à POO), et je me demandais si quelqu'un avait une solution élégante autre que globale dans chaque fonction . Toutes les suggestions sont grandement appréciées.php pdo connection scope
CONNEXION
class PDOConnectionFactory{
// receives the connection
public $con = null;
// swich database?
public $dbType = "mysql";
// connection parameters
// when it will not be necessary leaves blank only with the double quotations marks ""
public $host = "localhost";
public $user = "user";
public $senha = "password";
public $db = "database";
// arrow the persistence of the connection
public $persistent = false;
// new PDOConnectionFactory(true) <--- persistent connection
// new PDOConnectionFactory() <--- no persistent connection
public function PDOConnectionFactory($persistent=false){
// it verifies the persistence of the connection
if($persistent != false){ $this->persistent = true; }
}
public function getConnection(){
try{
// it carries through the connection
$this->con = new PDO($this->dbType.":host=".$this->host.";dbname=".$this->db, $this->user, $this->senha,
array(PDO::ATTR_PERSISTENT => $this->persistent));
// carried through successfully, it returns connected
return $this->con;
// in case that an error occurs, it returns the error;
}catch (PDOException $ex){ echo "We are currently experiencing technical difficulties. We have a bunch of monkies working really hard to fix the problem. Check back soon: ".$ex->getMessage(); }
}
// close connection
public function Close(){
if($this->con != null)
$this->con = null;
}
}
PAGE UTILISÉ SUR
include("includes/connection.php");
$db = new PDOConnectionFactory();
$conn = $db->getConnection();
function test(){
try{
$sql = 'SELECT * FROM topic';
$stmt = $conn->prepare($sql);
$result=$stmt->execute();
}
catch(PDOException $e){ echo $e->getMessage(); }
}
test();
pouvez-vous peut-être me montrer un exemple? – Scarface
@Scarface: Télécharger le framework TinyMVC et obtenir à partir du fichier plugins db.PDO_MVC.php là vous avez exemple – Svisstack