Home » Php » php – How to connect to a database with semicolon in the name?

php – How to connect to a database with semicolon in the name?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a database which has a semicolon in the name e.g. a;a. I can’t rename the database. In SQL I would use the backticks to escape the name, but how can I do it in PDO DSN?

$db = 'a;a';
$dsn = "mysql:host=localhost;dbname=$db;charset=utf8mb4";
$options = [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false,
];
try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int) $e->getCode());
}

Since ; is used as a separator in the DSN, PDO thinks my database is called a and I get this error:

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1049] Unknown database ‘a’

How to&Answers:

I solved it by using double semicolon.

$db = 'a;;a'; // <-- means the database is called `a;a`
$dsn = "mysql:host=localhost;dbname=$db;charset=utf8mb4";