class dbConnection {
public $pdo;
public function __construct() {
$this->dbConnect();
}
public function dbConnect() {
if((count($_POST) == 6)&&($_GET['a'] == "connect")) {
$host = $_POST['host'];
$port = $_POST['port'];
$username = $_POST['username'];
$password = $_POST['password'];
$database = $_POST['database'];
try{
$this->pdo = new PDO('mysql:host='.$host.';dbname='.$database.';port='.$port, $username, $password );
echo 'Connection successful!';
return $pdo;
}
catch(PDOException $e){
echo 'Error: ' . $e->getMessage();
}
}
}
}
class Group extends dbConnection { //Class for group, for ex. employe and employers.
public $name; // Name of group
public $pdo;
public function __construct ($_name, $conn) {
$this->pdo = $conn;
$this->name = $_name;
}
public function getGroupList() {
if(isset($this->pdo)) {
try
{
$conn = $this->pdo;
$conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //to catch exceptions
$stmt = $pdo -> query('SELECT id, Name, Skills FROM '.$this->name); //sql query with group name
$list = $stmt->fetchAll(PDO::FETCH_NUM); //fetch statement into array
$stmt -> closeCursor();
unset($stmt);
return var_dump($list); //gives pure data
}
catch(PDOException $e)
{
return 'There was some error: ' . $e->getMessage();
}
}
else {
$pdo;
}
}
}
And execution:
$conn = new dbConnection;
$workers = new Group("workers", $conn);
$workers->getGroupList();
I get error:
Call to undefined method dbConnection::setAttribute()
on line:
$conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //to catch exceptions
I’m trying to solve that, I don’t know why php treats PDO object as a method. I don’t have any idea. And I have to write more letters.
$this->pdoin that context references a dbConnection object. Really, you should change the name to$this->connor something similar for clarity.To fix it, try:
or specifically, in the context of your code:
However, it also seems you’re using Inheritance incorrectly.
Rather than passing a connection to the Group class, you should instead call the parent constructor so that it initializes properly, setting the value of pdo per its definition.
Try this:
From there, you can reference
$this->pdoas it’s defined in dbConnection