Reputation: 3224
I have set constants for database in connect.php.
connect.php
define('DB_HOST','localhost');
define('DB_NAME','dbname');
define('DB_USER','dbuser');
define('DB_PASSWORD','dbpass');
Here is the Database Class
require("connect.php");
class Database {
private $connect;
function opendb() {
$this->connect = new PDO(DB_NAME, DB_USER, DB_PASSWORD);
}
function closedb() {
$this->connect = null; //close connection
}
}
I get this error when i load the page that accesses the database class.
Fatal error: Uncaught exception 'PDOException' with message 'invalid data source name'
what did i do wrong?
Upvotes: 0
Views: 270
Reputation: 27855
You have to give the connection string here instead of the constant DB_NAME:
$this->connect = new PDO(DB_NAME, DB_USER, DB_PASSWORD);
like
$dsn = 'mysql:host=localhost;dbname='.DB_NAME;
$this->connect = new PDO(DB_NAME, DB_USER, DB_PASSWORD);
EDIT
you should also use the HOST constant as its defined.
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME;
Upvotes: 2
Reputation: 850
You need to use this -
$this->connect = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
Upvotes: 1