Madame Green Pea
Madame Green Pea

Reputation: 187

PDO is unable to fetch database name on SQL queries

I am trying to connect to the database via PDO and my db.php file is as follows:

$host = "localhost";
$db = "mydb";
$user = "user";
$pass = "qRES2fIWK8Gg";

try 
{
    $db = new PDO("mysql:host = $host; dbname = $db", $user, $pass);
    $db -> exec ("SET NAMES utf8"); // charset = utf8 doesn't work.
    echo "Database connection is successful. <br>";
}

catch (PDOException $e) 
{
    echo $e -> getMessage();
}

I have two problems which I think there is a connection between them.

  1. When I check the db.php, I can get Database connection is successful message even though I change the host and dbname with random and incorrect values. How is that possible? When I try the same process on the database username and password, it gives an error.

  2. I am unable to run SQL queries without stating database name in it as PDO doesn't fetch database name from db.php. For example, this SQL query doesn't work:

        SELECT * FROM settings WHERE settings_id= :id
    

    However, this one works successfully:

        SELECT * FROM mydb.settings WHERE settings_id= :id
    

I was working on localhost. After this problem, I thought it has been related to localhost and I moved my project to a virtual host. However, this step hasn't fixed the problems.

Upvotes: 0

Views: 232

Answers (1)

Guillaume Boudreau
Guillaume Boudreau

Reputation: 2887

Removing the spaces in your DSN string should resolve your issues:

"mysql:host=$host;dbname=$db"

Upvotes: 1

Related Questions