Q:

Error when creating MySQL Table with PDO

I have just created a MySQL database named "test2" using PDO. Now I'm trying to create a table named "Visiteurs" but it seems my code do not work properly. 
The error echoed is:

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

(which is wrong I think) and my code is the following: 
$serveur  = "localhost";
$login = "root";
$pass = "root";

        try{
            $conn = new PDO("mysql:host = $serveur; dbname = test2", $login, $pass);

            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $codesql = "CREATE TABLE Visiteurs (
                id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                nom VARCHAR(50) NOT NULL,
                prenom VARCHAR(50) NOT NULL,
                email VARCHAR(70)
            )";

            $conn->exec($codesql);
            echo 'Table "Visiteurs" créée !';
        }

        catch(PDOException $e) { 
            echo 'Echec : ' . $e->getMessage(); 
        }

Can someone help me find where is the error? 

A:

Althout the PDO MySQL DSN string documentation is not specific about whitespace, experience tells me that whitespace is not permitted in a DSN string.  Since you have dbname = test2, the dbname is not actually being parsed and used, so PDO complains that no database was selected. Your DSN should look like the following, with no spaces between the key=value pairs:
"mysql:host=$serveur;dbname=test2"

You mentioned in comments that a previous connection succeeded and you were able to issue a CREATE DATABASE statement. That was only due to the coincidence of the default host being localhost and your $serveur variable being set to localhost as well.  PDO probably did not parse the host= parameter from the DSN, but instead used localhost as the default connection with your user credentials. Since a CREATE DATABASE statement does not need to have a database selected, the dbname= was irrelevant.

