Invalid Data Source PDO PHP MySQL

1

I'm having problems with the PDO connection to the 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;
        }

    }
    ?>

You are returning this error when trying to login with username 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-> constructor ('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 problem only in the connection with the database?

    
asked by anonymous 05.09.2016 / 15:34

1 answer

4

In your code, you have to specify the driver of which bank to use, 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 sprintf() function instead of this concatenation. If you want you can replace the string mysql with 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);
}
    
05.09.2016 / 15:46