简单的php PDO无效的目录名称:1046未选择数据库

This may be really simple issue, but I can't find solution. If I have

$query = $conn->query("SELECT * FROM dbName.users");

everything works fine, but without dbName it cause error:

SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected.

Here is the code

$Host     = "localhost";
$Name     = "test";
$User     = "test";
$Password = "";

try {
    $conn = new PDO("mysql:host=$Host;dbName=$Name", $User, $Password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $query = $conn->query("SELECT * FROM users");
    while($r = $query->fetch()){
        echo $r['login']." ".$r['pass']."<br>";
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

Does anyone knows, why it works only with dbName before table name? How can i fix it? Thanks!

I was able to reproduce your problem.

$conn = new PDO("mysql:host=$Host;dbName=$Name", $User, $Password);
//                            use dbname instead

Apparently the dbName in your DSN string is case sensitive. It should be dbname. After I changed that it worked.


Just FYI for anyone else who happens upon this, I messed with it a bit more, and it looks like all of the parameter names in the DSN seem to be case sensitive, (and I was testing this on Windows, where some things aren't.) Better just do it like it looks in the documentation.