I am getting an error: Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)' in /home/content/........
Althought if I do it in one file, it works fine!
My php file:
<?php
require 'includes/dbc.php';
$dbc = new dbc();
$db = $dbc->openDb();
$stmt = $dbc->getAllUsers($db);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['iduser'];
}
?>
my database class:
<?php
class dbc {
public $dbserver = '';
public $dbusername = '';
public $dbpassword = '';
public $dbname = '';
function openDb() {
$db = new PDO('mysql:host=' . $dbserver . ';dbname=' . $dbname . ';charset=utf8', '' . $dbusername . '', '' . $dbpassword . '');
return $db;
}
function getAllUsers($db) {
$stmt = $db->query("SELECT * FROM user");
return $stmt;
}
}
?>
In the sample-code you provided, you’re not specifying a database, user, password or host to the database connection string:
With invalid data, your code cannot connect and therefore you’re receiving the connection-error.
As they’re global to the
dbcclass, you’ll need to use$thiswhen accessing them (such as$this->dbserver). Try updating your code to:* Also, though you may have removed it to post the question, you don’t have any of those variables set to actual values either.