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?