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;
}
}
}
和执行:
$conn = new dbConnection;
$workers = new Group("workers", $conn);
$workers->getGroupList();
我得到错误:
在线调用未定义的方法 dbConnection::setAttribute():
$conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //to catch exceptions
我正在尝试解决这个问题,我不知道为什么 php 将 PDO 对象视为一种方法。我没有任何想法。我必须写更多的信。