0

I simply have a pdo object and I want to use it to connect to my online database, but it's not working and I cant find why.

I got a PHP error:

Uncaught exception 'PDOException' with message 'invalid data source name'

in my constructor

My pdo constructor:

<?php 

class PdoGsb{   
        
        private static $serveur='mysql.hostinger.fr';
        private static $bdd='dbname=****';          
        private static $user='****';
        private static $mdp='****';
        private static $monPdo;
        private static $monPdoGsb=null;

    private function __construct(){
        PdoGsb::$monPdo = new PDO(PdoGsb::$serveur.';'.PdoGsb::$bdd, PdoGsb::$user, PdoGsb::$mdp); 
        PdoGsb::$monPdo->query("SET CHARACTER SET utf8");
        PdoGsb::$monPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    public function _destruct(){
        PdoGsb::$monPdo = null;
    }

    public  static function getPdoGsb(){
        if(PdoGsb::$monPdoGsb==null){
            PdoGsb::$monPdoGsb= new PdoGsb();
        }
        return PdoGsb::$monPdoGsb;  
    }
    
    public function setClient($sexe, $age){
        $req="INSERT INTO client (sexe, age)
         VALUES
         ('$sexe', '$age');";
         $res2= PdoGsb::$monPdo->exec($req);
    }
    
}
?>

file in which I send my data:

<?php
    require_once ("rees.php");
        
    $pdo = PdoGsb::getPdoGsb();     
 
$sexe = "homme";
$age = "55";

    $pdo->setClient($sexe, $age);
?>
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Mirnox
  • 3
  • 1

1 Answers1

1

IMO it's worth to put the connection in a getConnection method. And then you could call it inside the constructor, but it's up to you. I would change this:

private static $bdd='dbname=****';   

to this:

private static $bdd='****';   

and then, try this:

try{
PdoGsb::$monPdo = new PDO("mysqlhost:host=" . $serveur ."dbname=". $bdd,$user,$mdp;
}catch (PDOException $exception) {
            echo "Failed to connect:  " . $exception->getMessage();
            exit();
}
return $this->$monPdo;
taavs
  • 659
  • 9
  • 15