Invalid Mysql PHP PDO Data Source

Asked

Viewed 1,034 times

1

I’m having problems connecting PDO to mysql database.

Database_connection.php:

<?php
    class Database_connection {

        private $db_host =  "local";
        private $db_name = "root";
        private $db_user = "user";
        private $db_pass = "pass";
        protected $db_holder;

        protected function open_connection() {
            $this->db_holder = new PDO($this->db_host.$this->db_name, $this->db_user, $this->db_pass);
        }

        protected function close_connection() {
            $this->db_holder = null;
        }

    }
    ?>

Is returning these errors when I try to log in with user and password:

Fatal error: Uncaught Exception 'Pdoexception' with message 'invalid data source name' in Database_connection.php:11 Stack trace:
/Database_connection.php(11): PDO->__Construct('local', 'user', 'pass') /iis_functions_home.php(9): Database_connection->open_connection() /log_in_validation.php(13): Iis_functions_home->check_username('username', 'password') #3 {main} thrown in /Database_connection.php on line 11

Do I need to post any more code? Or is the connection only problem with the database?

  • Are you passing your correct database path? have tried connecting directly through the database?

1 answer

5


In your code failed to specify the driver of which database will be used, it is always the first thing to declare and also the database.

The correct syntax is:

new PDO('mysql:host=localhost;dbname=base', $usuario, $senha);

Change:

new PDO($this->db_host

To:

new PDO('mysql:host='. $this->db_host .';dbname='.$this->db_name, $this->db_user, $this->db_pass);

Another alternative is to mount dsn with the function sprintf() instead of this concatenation. If you want you can replace the string mysql by a property.

protected function open_connection() {
   $dsn = sprintf('mysql:host=%s;dbname=%s', $this->db_host, $this->db_name);
   $this->db_holder = new PDO($dsn, $this->db_user, $this->db_pass);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.