Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql - PDO Error - Invalid catalog name: 1046 No database selected

I have a problem with PDO, and I see absolutely no where he come. I can not question my MySQL database. Just to test I used the following code (having quite sour previously configured the parameters for the connection:

try {
    $dbh= new PDO('mysql:host=serverName;dbname=Mydatabase','user','password');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (Exception $e) {
    die('Erreur : ' . $e->getMessage());
}

var_dump($dbh);    // gives : object(PDO)#1 (0) { }

$res=$dbh->query('SELECT * FROM table');

The connection is made correctly with MySQL but after query I get this error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' in /home/outout/public_html/file.php:16 Stack trace: #0 /home/outout/public_html/file.php(16): PDO->query('select * from t...') #1 {main} thrown in /home/outout/public_html/file.php on line 16.

The code works on a local machine, but as soon as I put it online (cPanel) it shows me this error. Do I have to configure PDO in .htaccess?

I absolutely do not understand where the problem come. Someone would have an idea?

like image 962
Benss Avatar asked Feb 26 '15 23:02

Benss


4 Answers

Help Mysql resolve the handle by.

Instead of:

$res=$dbh->query('SELECT * FROM table');

Try:

$res=$dbh->query('SELECT * FROM Mydatabase.table');
like image 180
Codehonor Avatar answered Nov 14 '22 20:11

Codehonor


I faced the same problem while not mentioning the 'host' string with 'mysql' (mysql:host). I solved the problem by following code.

class Database{
    protected static $pdo;
    public function __construct(){}

    public function connect(){
        $dsn="mysql:host=localhost;dbname=dbname";
        try{
        self::$pdo = new PDO($dsn,"root","");
        self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
        echo 'Connected';
        return self::$pdo;
        }catch(PDOException $ex){
            echo $ex->getMessage();
        }
        return false;
    }
    public function getConnection(){
        return self::$pdo;
    }
}
like image 42
Faiz Ahmed Avatar answered Nov 14 '22 20:11

Faiz Ahmed


Instead of:

$res=$dbh->query('SELECT * FROM table');

just do:

  $res=$dbh->query('SELECT * FROM dbname.tablename');

You will be good to go.

like image 44
Aditya Wankhede Avatar answered Nov 14 '22 21:11

Aditya Wankhede


I faced same problem. Resolution of problem was removed the space between hostname and dbname variable as follows: From: $conn = new PDO("mysql:host = $servername;dbname = $dbname", $username, $password);

To: $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

like image 31
Prabhat Kumar Avatar answered Nov 14 '22 20:11

Prabhat Kumar