我是在PHP中使用PDO的新手,我在这里需要一些帮助:
我创建了两个类,第一个是数据库连接,第二个是模型。
我唯一想要的是打印数据库的元素,但我总是得到同样的错误:
Call to a member function query() on a non-object
我有以下PHP代码:
<?php
class DBConnection {
private $dbConnected;
public function __construct() {
}
public function iniciarConexion() {
$this->dbConnected = new PDO('pgsql:host=localhost;dbname=db', 'user', '123456');
}
public function cerrarConexion() {
/* Write Something */
}
}
class Sectores extends DBConnection {
private $conexion;
public function __construct() {
$this->conexion = new DBConnection();
$this->conexion->iniciarConexion();
}
public function ObtenerSectores() {
$sql = "SELECT 'sector' FROM sector ORDER BY numero";
$resultado = $this->conexion->iniciarConexion->query($sql);
foreach ($resultado as $row) {
print $row['numero'] . "\t";
print $row['sector'] . "\t";
}
}
}
$Sectores = new Sectores();
$Sectores->ObtenerSectores();
?>
顺便说一句,pgsql运行良好,我已经测试过了。
有什么想法吗?
答案 0 :(得分:1)
您正在调用错误的变量。您扩展了类DBConnection,因此默认情况下您已具有其功能。
class Sectores extends DBConnection {
public function __construct() {
$this->iniciarConexion();
}
public function ObtenerSectores() {
$sql = "SELECT 'sector' FROM sector ORDER BY numero";
$resultado = $this->dbConnected->query($sql);
foreach ($resultado as $row) {
print $row['numero'] . "\t";
print $row['sector'] . "\t";
}
}
}