0

Today I'm trying to connect to multiple database (I hope I'm calling it right) with one PDO, so my code looks like this:

class DB{
    private $con;
    private $DATABASE_HOST = 'localhost';
    private $DATABASE_USER = 'root';
    private $DATABASE_PASS = '';
    private $DATABASE_NAME = 'phplogin';
    
    public function __construct(){
        $dsn = "mysql:host=$this->DATABASE_HOST;dbname=$this->DATABASE_NAME";

        try {
            $this->con = new PDO($dsn, $this->DATABASE_USER, $this->DATABASE_PASS);
            $this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
    }

    public function viewData($database){
        $query = "SELECT nome FROM :name";
        $stmt = $this->con->prepare($query);
        $stmt->execute(['name' => $database]);
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $data;
    }
}

Doing like that it throws me an error for $database because it tell me that there is a Syntax error or access violation. Now, what I want to do is to give to $database the name of the database I want to connect with when i call the function, but I don't know which is the right way, I thought that PDO could help me but I can't understand why it doesn't work... Can anyone help me?

Elizzit
  • 11
  • 3
  • Remove `try {` from your code – Dharman Apr 23 '21 at 16:39
  • use this `$dsn = "mysql:host={$this->DATABASE_HOST};dbname={$this->DATABASE_NAME}"`; – ha3an Apr 23 '21 at 16:41
  • @Dharman why should remove try? – ha3an Apr 23 '21 at 16:45
  • @ha3an Because it is causing a PHP syntax error – Dharman Apr 23 '21 at 16:48
  • @Dharman you right try with out catch causing PHP syntax error – ha3an Apr 23 '21 at 16:51
  • is not ```try``` or the ```$dsn``` the problem, both of them don't throw me error. Is just the ```$database``` that cause me the syntax error. If instead of ```:name``` i put the name of the database and I remove what's inside the parentheses of the execute it work, so the problem is the ```$database```. (And try without catch don't cause syntax error to me) – Elizzit Apr 23 '21 at 16:52
  • No, try is not the main problem although it will prevent PHP code from running. The problem you are describing is solved in the answer I provided – Dharman Apr 23 '21 at 17:03

0 Answers0