PHP OOP undefined > method stdClass - php

I'm new in OOP and I have 2 classes.
class db{
private $_database;
public function __construct(){
try{
$this->_database = new PDO('mysql:host='.'localhost'.';dbname='.'lala','root','');
}catch(PDOExeption $e){
die($e->getMessage());
}
}
public function query(){
$query = $this->_database->query('SELECT * FROM users');
$query->setFetchMode(PDO::FETCH_OBJ);
$query->execute();
$row = $query->fetchAll();
return $row;
}
}
first class is database.
class users{
public $id, $name, $password, $mail;
private $_databaseUSERS, $_result;
public function __construct(){
$this->_databaseUSERS = new db();
}
public function nameAndpass(){
echo "Name: {$this->name}, Password: {$this->password}".'<br>'.'<br>'.'<br>'.'<br>';
}
public function get(){
$this->_result = $this->_databaseUSERS->query();
$object_array = array();
foreach ($this->_result as $key => $value) {
$object_array[] = self::blabla($value);
}
return $object_array;
}
public function blabla($record){
foreach($record as $attribute => $value){
$this->$attribute = $value;
}
return $record;
}
}
and second class is users.
$users = new users();
$users->get();
echo $users->nameAndpass();
echo $users->mail.'<br>'
this is working and output is:
Name: Johny, Password: 123456
Johny#mail.com
$users = new users();
$user = $users->get();
foreach ($user as $userss) {
echo $userss->name.'<br>';
}
this is also working and output is:
Jack
Billy
Johny
$users = new users();
$user = $users->get();
foreach ($user as $userss) {
echo $userss->nameAndpass().'<br>';
}
this is not working and ouput is: Fatal error: Call to undefined
method stdClass::nameAndpass() in
C:\Users\Irakli\Desktop\Work\xamp\htdocs\index.php
How can I fix this error?

Related

How to get everything outside the database with foreach and class

I have a problem. I want some data out my database.
I have two page's a categorie.php here I want that he shows everything out the database. And I have a second page. Here are my classes. I have trying a foreach on the categorie.php but if I do that, than shows he 1 thing out the database 4 times the same and not the another data.
Below you can see my code.
I hope that you can help me.
Thank you.
This is my categorie.php
<?php
require_once '../app/functions/second.php';
require_once '../app/db/dbpassword.php';
require_once 'include/head.php';
if (isset($_GET['categorie']) && !empty($_GET['categorie'])) {
$id = $_GET['categorie'];
$dbh = new PDO("mysql:host=$host; dbname=$dbname;", $usernamedb,
$passworddb);
$cate = new Categorie($dbh);
$cate->loadCate($id);
// $page->loadId($id);
$categorie = $cate->getCategorie();
$titel = ucwords($categorie);
?>
<h2 class="center_h2"><?= $titel ?></h2>
<?php foreach ($cate as $key) {
$titelart = $cate->getTitel();
$beschrijving = $cate->getBeschrijving();
$plaatje = $cate->getImage();
$id = $cate->getId();
var_dump($titelart);
} ?>
<?php
} else {
echo "Dit bericht is verwijderd of is verplaats.";
}
require_once 'include/footer.php';
?>
This is my class page
<?php
class Categorie {
protected $dbh;
public function __construct($new_dbh){
$this->dbh = $new_dbh;
}
public function loadCate($cate){
$query = $this->dbh->prepare('SELECT * FROM schilderijen WHERE categorie=?');
$query->execute(array($cate));
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
$this->id = $row->id;
$this->categorie = $row->categorie;
$this->titel = $row->titel;
$this->beschrijving = $row->beschrijving;
$this->plaatje = $row->plaatje;
}
}
public function getId(){
return $this->id;
}
public function getCategorie(){
return $this->categorie;
}
public function getTitel(){
return $this->titel;
}
public function getBeschrijving(){
return $this->beschrijving;
}
public function getImage(){
return $this->plaatje;
}
}
?>
Ok so you have a problem with the use of your class. In the while after your SQL request, you apply the value the instance variable like $this->id = $row->id; but this variable will be rewrite with the next row value.
Use a static function for your SQL request and return an array of Categorie like that :
class Categorie {
protected $id, $categorie, $title, $beschrijving, $plaatje;
public function __construct($id, $categorie, $title, $beschrijving, $plaatje){
$this->id = $id;
$this->categorie = $categorie;
$this->title = $title;
$this->beschrijving = $beschrijving;
$this->plaatje = $plaatje;
}
public static function loadCate($dbh, $cate){
$query = $dbh->prepare('SELECT * FROM schilderijen WHERE categorie=?');
$query->execute(array($cate));
$res = array();
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
$res[] = new Categorie($row->id, $row->categorie, $row->titel, $row->beschrijving, $row->plaatje);
}
return $res;
}
public function getId(){
return $this->id;
}
public function getCategorie(){
return $this->categorie;
}
public function getTitle(){
return $this->title;
}
public function getBeschrijving(){
return $this->beschrijving;
}
public function getImage(){
return $this->plaatje;
}
}
And you can use it like that:
$categories = Categorie::loadCate($dbh, $id);
foreach($categories as $categorie){
var_dump($categorie->getTitle());
}

PHP object is not being created

I have received the following error:"Fatal error: Call to a member function session_type() on a non-object".
Supposedly I'm not creating an object in the variable "$tabsessiontype2". I don't see the reason why the object isn't created. Thanks for you help.
Here is my TeacherController.php
if(isset($_POST['search']) && $_POST['sessiontype_name']){
$tabsessiontype2=Db::getInstance()->select_session_type2($_POST['sessiontype_name']);
if($tabsessiontype2->session_type()=='X'){
$view='teacher.php';
}
elseif($tabsessiontype2->session_type()=='XO'){
$view='teacherxo.php';
}
elseif($tabsessiontype2->session_type()=='note'){
$view='teachernote.php';
}
}
This is the function I call:
public function select_session_type2($name_session_type) {
$query = "SELECT * FROM session_types WHERE session_types.name_session_type='$name_session_type'";
$result = $this->_db->query($query);
$tableau = array();
if ($result->rowcount()!=0) {
while ($row = $result->fetch()) {
$tableau[] = new Sessiontype($row->code_session_type,$row->name_session_type,$row->quarter_session_type,$row->code_lesson,$row->session_type);
}
}
return $tableau;
}
Here is the SessionType class:
class SessionType{
private $_code_session_type;
private $_name_session_type;
private $_quarter_session_type;
private $_code_lesson;
private $_session_type;
public function __construct($code_session_type,$name_session_type, $quarter_session_type, $code_lesson,$session_type){
$this->_code_session_type = $code_session_type;
$this->_name_session_type = $name_session_type;
$this->_quarter_session_type = $quarter_session_type;
$this->_code_lesson = $code_lesson;
$this->_session_type = $session_type;
}
public function code_session_type(){
return $this->_code_session_type;
}
public function name_session_type(){
return $this->_name_session_type;
}
public function quarter_session_type(){
return $this->_lastname;
}
public function code_lesson(){
return $this->_email_student;
}
public function session_type(){
return $this->_session_type;
}
}
It looks like the function select_session_type2 is returning an array:
$tableau = array();
if ($result->rowcount()!=0) {
while ($row = $result->fetch()) {
$tableau[] = new Sessiontype($row->code_session_type,$row->name_session_type,$row->quarter_session_type,$row->code_lesson,$row->session_type);
}
}
return $tableau;
and you are expecting an object:
$tabsessiontype2=Db::getInstance()->select_session_type2($_POST['sessiontype_name']);
if($tabsessiontype2->session_type()=='X'){
$view='teacher.php';
}

How can I complete my dropdown with database data?

I'm building an application based on Slim Framework, and I already have some working code. To return a JSON response with a list of projects, I wrote the following:
Controller class (controllerProyectos.php)
<?php
require "transferController/transferProyectos.php";
class NombreProyecto {
public function getProyectos() {
$list = array();
foreach ($this->fillObject() as $sKey => $oValue) {
$list[] = array(
'id' => $oValue->getId(),
'nombre_proyecto' => $oValue->getNombre(),
'state' => $oValue->getState(),
);
}
return $list;
}
private function fillObject() {
$aObjects = array();
for ($i = 0; $i < 5; $i++) {
$oTransfer = new TransferProyeCtr();
$oTransfer->setId($i);
$oTransfer->setNombre("proyecto " . $i);
$oTransfer->setState(1);
$aObjects[] = $oTransfer;
}
return $aObjects;
}
}
Front controller (index.php)
<?php
require "vendor/autoload.php";
$sPathApi = "/api/sistemaTareas/";
$app = new \Slim\Slim();
$app->get($sPathApi . $sVersion . 'proyectos', function () {
require "controller/controllerProyectos.php";
$oProyecto = new NombreProyecto();
header('Content-Type: application/json');
echo json_encode($oProyecto->getProyectos());
exit();
});
Model class (transferProyectos.php)
<?php
class TransferProyeCtr {
private $sNombre;
private $iId;
private $iState;
public function getNombre() {
return $this->sNombre;
}
public function setNombre($nombre) {
$this->sNombre = $nombre;
}
public function getId() {
return $this->iId;
}
public function setId($Id) {
$this->iId = $Id;
}
public function getState() {
return $this->iState;
}
public function setState($state) {
$this->iState = $state;
}
}
As you can see I'm using some mockup data in the controller. When I do an AJAX request to my application, I get the following result in a dropdown:
- proyecto 1
- proyecto 2
- proyecto 3
- proyecto 4
- proyecto 5
So far everything is working as expected. But I'd like to return real data from the database in that controller.
I wrote a function (inside bdconnection.php file) to open the database connection:
<?php
function connect_db() {
$server = 'localhost';
$user = 'root';
$pass = '123asd';
$database = 'bd_actividades';
$connection = new mysqli($server, $user, $pass, $database);
return $connection;
}
I think that in my controller I need something like:
public function getPro() {
require "sistema/bdconnection.php";
$sql = "select pro_nombre FROM act_proyecto";
try {
$db = connect_db();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
echo json_encode($e->getMessage());
}
}
And replace $oTransfer->setNombre("proyecto " . $i); for $oTransfer->setNombre($users);, but I'm not sure.
Just to give you guys a little more detail about my application, here will go the files structure and database data:

json_encode : values showing null

<?php
require_once (realpath(dirname(__FILE__) . '/../includes/database.php'));
class User {
public $email;
public $password;
public function find_email($email, $password) {
global $database;
$pswd = substr(md5($password), 0, 25);
$results_array = self::find_by_sql("SELECT * FROM tbl_users where email_id='".$email."' AND password='".$pswd."'");
return !empty($results_array)? array_shift($results_array) : false;
}
public static function find_by_sql($sql){
global $database;
$results = $database -> query($sql);
$object_array = array();
while($row = $database -> fetch_array($results)){
$object_array[] = self::instantiate($row);
}
return $object_array;
}
public static function instantiate($row) {
$event = new self;
foreach($row as $attribute => $value) {
if($event -> has_attribute($attribute)) {
$event -> $attribute = $value;
}
}
return $event;
}
private function has_attribute($attribute) {
$object_vars = get_object_vars($this);
return array_key_exists($attribute, $object_vars);
}
}
if (isset($_GET['email']) && isset($_GET['password'])) {
$result = new User();
$result->find_email($_GET['email'], $_GET['password']);
echo json_encode($result);
}
?>
This is the login.php which is supposed to print out the json for the required user, but whenever I try to get the json, this is getting returned.
{"email":null,"password":null}
Any help would be appreciated. Thanks.
You don't do anything with the result of find_email. Your class doesn't update it's own properties when find_email is called. Instead, it returns a new instance of the class with the email and password properties set, so you need to capture the return value and encode that.
Change to:
$result = new User();
$user = $result->find_email($_GET['email'], $_GET['password']);
echo json_encode($user);
Side note: have a look at SOLID and Dependency Injection. DI would be preferred over having a global $Database.

PHP5 variable scope and class construction

I'm having problems with accessing variables from my classes...
class getuser {
public function __construct($id) {
$userquery = "SELECT * FROM users WHERE id = ".$id."";
$userresult = mysql_query($userquery);
$this->user = array();
$idx = 0;
while($user = mysql_fetch_object($userresult)){
$this->user[$idx] = $user;
++$idx;
}
}
}
I'm setting this class in a global 'classes' file, and later on I pass through a user id into the following script:
$u = new getuser($userid);
foreach($u->user as $user){
echo $user->username;
}
I'm hoping that this will give me the name of the user but it's not, where am I going wrong?!
Thanks
please define your users member as public in your class like this
class getuser {
public $user = null;
//...
}
in order to access a class property, you have to declare it public or implement getters and setters (second solution is preferable)
class A {
public $foo;
//class methods
}
$a = new A();
$a->foo = 'whatever';
with getters and setters, one per property
class B {
private $foo2;
public function getFoo2() {
return $this->foo2;
}
public function setFoo2($value) {
$this->foo2 = $value;
}
}
$b = new B();
$b->setFoo2('whatever');
echo $b->getFoo2();
in your example:
class getuser {
private $user;
public function __construct($id) {
$userquery = "SELECT * FROM users WHERE id = ".$id."";
$userresult = mysql_query($userquery);
$this->user = array();
$idx = 0;
while($user = mysql_fetch_object($userresult)){
$this->user[$idx] = $user;
++$idx;
}
}
/* returns the property value */
public function getUser() {
return $this->user;
}
/* sets the property value */
public function setUser($value) {
$this->user = $value;
}
}
$u = new getuser($userid);
$users_list = $u->getUser();
foreach($users_list as $user) {
echo $user->username;
}

Categories