Cześć,
Piszę REST API, zatrzymałem się na etapie wczytywania wartości z MySQL do JSON'a.
Wyskakuje mi błąd "Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\Lignum\uzytkownik.php:19" wygląda na to że funkcja read() nic nie pobiera z bazy danych.
Otrzymuje pusty array()
{"body":[],"count":0}
Mój kod:
<?php
class User{
private $polaczenie;
public $id;
public $login;
public $password;
public function __construct($Dbclass){
$this->polaczenie = $Dbclass;
}
public function read(){
$query = "SELECT id, login, password FROM users ";
$stmt = $this->polaczenie->prepare($query);
$stmt->execute();
return $stmt;
}
}
?>
<?php
header("Content-Type: application/json; charset=UTF-8");
include_once './polaczenie.php';
include_once './uzytkownik.php';
$Dbclass = new DBclass();
$polaczenie = $Dbclass->GetConnection();
$user = new User($polaczenie);
$stmt = $user->read();
$count = $stmt->rowCount();
if($count > 0){
$user = array();
$user["body"] = array();
$user["count"] = $count;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$u = array(
"id" => $id,
"login" => $login,
"password" => $password
);
array_push($user["body"], $u);
}
echo json_encode($user);
}
else{
echo json_encode(array("body" => array(), "count" => 0));
}
?>
polaczenie z baza
<?php
class DBclass {
private $host = '127.0.0.1';
private $username = 'root';
private $password = '';
private $database = 'lignum';
public $connection;
public function GetConnection(){
try{
$this->connection = null;
$this->connection = new PDO('mysql:host='.$this->host.';dbname='.$this->database,$this->username, $this->password);
$this->connection->exec("set names utf8");
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
return $this->connection;
}
};
?>
<?php
include_once './configuracja.php';
try{
$Dbclass = new DBclass();
$polaczenie = $Dbclass->GetConnection();
}
catch(Exception $e){
echo "< polaczenie.php -> blad > ";
}
?>