Reputation: 4900
Here is my program description. I tried to create a Database connection class that has different method which differ in the way they pull the records from the database.
What I'm trying to do is -- setting the class attributes to the PDO connection parameters and creating a default constructor with those attributes. Whenever I need data, I will call those methods which are supposed to return records.
Question is : I suppose that my connection string for creating the PDO object is right, but It will show error saying Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Can you please help me out to figure out whats really going on ? And also can you please share with me the techniques and ideas to create secure, robust and dynamically accessible database classes or methods? I would highly appreciate. Thanks in advance!
Code :
<?php
class DatabaseConnection {
private $hostname;
private $dbname;
private $username;
private $password;
public function __construct() {
$this->hostname = "hostname";
$this->dbname = "database";
$this->username ="username";
$this->password = "password";
}
function getDataFromTable($query){
echo $dns;
$db = new PDO("mysql:host = {$this->hostname} ; dbname = {$this->dbname}", $this->username, $this->password);
// stuffs ...
}
}
?>
Upvotes: 2
Views: 7890
Reputation: 12665
Clear the whitespaces:
$db = new PDO(
"mysql:host={$this->hostname};dbname={$this->dbname};charset=utf8",
$this->username,
$this->password
);
With PHP >= 5.3.6 you can add the charset to the dsn. (charset=utf8
)
Another possible problem: (http://php.net/manual/de/ref.pdo-mysql.connection.php)
When the host name is set to "localhost", then the connection to the server is made thru a domain socket. If PDO_MYSQL is compiled against libmysqlclient then the location of the socket file is at libmysqlclient's compiled in location. If PDO_MYSQL is compiled against mysqlnd a default socket can be set thru the pdo_mysql.default_socket setting.
So try with 127.0.0.1
instead of localhost
for the hostname or look here.
Upvotes: 5