简体   繁体   English

没有数据库名称的 Pdo 连接?

[英]Pdo connection without database name?

I'm trying to create a CMS and I want to make my client life easier so I create the database by myself.我正在尝试创建一个 CMS,我想让我的客户生活更轻松,所以我自己创建了数据库。 I encountered a problem while trying to do this.我在尝试执行此操作时遇到了问题。 The database isn't created so I can't connect with a PDO connection and mysql is deprecated so I can't use it.未创建数据库,因此我无法使用 PDO 连接进行连接,并且不推荐使用mysql ,因此我无法使用它。 Do you have any advice for me on how I can create a PDO connection before the database is created?关于如何在创建数据库之前创建 PDO 连接,您对我有什么建议吗? like a mysql_select_db() alternative?mysql_select_db()替代品?

You can start a PDO connection by this, correct me if I'm wrong:您可以通过此启动 PDO 连接,如果我错了,请纠正我:

$db = new PDO("mysql:host=localhost", 'user', 'pass');

The difference from this with a normal connection is the removed part dbname=[xx] , as you see.如您所见,与普通连接的区别在于删除了部分dbname=[xx]

Also a free tip when you want to use a UTF8 connection:当您想使用 UTF8 连接时,还有一个免费提示:

$db = new PDO("mysql:host=localhost;charset=UTF-8", 'user', 'pass');

In order to the comment of Yehonatan you can select a database by:为了对Yehonatan的评论,您可以通过以下方式选择数据库:

$db->exec('USE databaseName');

Simply drop the dbname= part:只需删除dbname=部分:

try {
    $pdo = new PDO("mysql:host=localhost;", "user", "pass");
    $stmt = $pdo->query("SHOW DATABASES");
    var_dump($stmt->fetchAll(PDO::FETCH_ASSOC));
}
catch (PDOException $e) {
    echo $e->getMessage();
}

Gives me给我

array(11) {
  [0]=>
  array(1) {
    ["Database"]=>
    string(18) "information_schema"
  }
  [1]=>
  array(1) {
    ["Database"]=>
    string(5) "cdcol"
  }
  [2]=>
  array(1) {
    ["Database"]=>
    string(5) "chica"
  }
  [3]=>
  array(1) {
    ["Database"]=>
    string(9) "downloads"
  }
  [4]=>
  array(1) {
    ["Database"]=>
    string(5) "mysql"
  }
  [5]=>
  array(1) {
    ["Database"]=>
    string(18) "performance_schema"
  }
  [6]=>
  array(1) {
    ["Database"]=>
    string(10) "phpmyadmin"
  }
  [7]=>
  array(1) {
    ["Database"]=>
    string(8) "rishumon"
  }
  [8]=>
  array(1) {
    ["Database"]=>
    string(4) "test"
  }
  [9]=>
  array(1) {
    ["Database"]=>
    string(5) "users"
  }
  [10]=>
  array(1) {
    ["Database"]=>
    string(7) "webauth"
  }
}

as expected.正如预期的那样。

我发现唯一可行的方法是在运行任何查询之前使用$pdo->query('USE databasename')设置默认数据库。

Using an empty string also works, eg dbname=;也可以使用空字符串,例如dbname=; no need to add more logic to get rid of all the dbname parts.无需添加更多逻辑来摆脱所有 dbname 部分。

$db_name = '';

$pdo = new PDO(
    sprintf('mysql:host=%s;dbname=%s;charset=%s',
        $db_host, $db_name, $db_charset),
    $db_user,
    $db_pass
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM