PDO is unable to fetch database name on SQL queries

153
August 19, 2018, at 11:40 AM

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.

Answer 1

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

"mysql:host=$host;dbname=$db"
Rent Charter Buses Company
READ ALSO
Sorting array by date in PHP

Sorting array by date in PHP

I'm tryin' to sort an array by date, but the result seems offAs you can see in the picture below the 0 index should be in the last

184
PHP - why should I use pathinfo when I can get it through $_File array

PHP - why should I use pathinfo when I can get it through $_File array

why should I use this code to get the name of the file?

127
How to enhance C.R.A.P. index for a switch-like function?

How to enhance C.R.A.P. index for a switch-like function?

I have a very typical switch-like function that returns a clasiffication for a given input value (Body Mass Index in this case)(I'm working with this function, but it could be any other of the same nature)

145