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);
?>
2

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.