4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Fatal error: Uncaught PDOException: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected inにハマった話

Last updated at Posted at 2021-06-19
<?php

// DSN(データソースネーム)
const DB_HOST = 'mysql:dbname = test_php; host = 127.0.0.1; charset = utf8';
const DB_USER = 'php_user';
const DB_PASSWORD = 'password';

try {
    $pdo = new PDO(DB_HOST, DB_USER, DB_PASSWORD,[
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
    ]);
    echo "DBに接続されました";

} catch(PDOException $e){
    echo "DBに接続されていません". "<br>". $e->getMessage();
    exit();
}

$sql = 'select * from contacts where id = 2';
$stmt = $pdo->query($sql); 
$result = $stmt->fetchAll();

var_dump($result);

実際に画面を表示してみると「DBに接続されました」と表示されているのに
最後のvar_dumpの出力結果では下記のエラーとなる。

Fatal error: Uncaught PDOException: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected in

・・・なんでだ??
イロイロ調べた結果、DSNが間違っているのではないかとのこと。
じっくりじっくり調べてもスペルミスではなさそう。。。うーーん :sweat_smile:

【結論】 やっぱりDSNの記述が間違っていた!!!
dbnameの前後にスペースを入れるとスペースも認識されてしまうため、スペースがあるとエラーになるらしい!
あとhostは「127.0.0.1」よりも「localhost」の方が好まれる?みたい。。。
以上、自分用備忘録 :writing_hand_tone1:

//NG(スペースあり)
const DB_HOST = 'mysql:dbname= test_php; host = 127.0.0.1; charset = utf8';

//OK(スペースなし)
const DB_HOST = 'mysql:dbname=test_php;host=localhost;charset=utf8';
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?