Call to a member function show() on string on line 15 - php

It worked a week before, I check if the objects are being defined with function class_exists() and they are both fine.
My error:
Call to a member function show() on string on line 15
Which is a function of class $logged_user in profile.php
echo $logged_user->show("Email");
My object $logged_user looks like this:
class LOGGED_USER
{
private $DB;
private $ID;
private $Firstname;
private $Surname;
private $DisplayName;
private $Gender;
private $Birth;
private $Email;
private $Level;
private $FolderPath;
private $LastLogin;
private $LastIP;
private $LevelWord;
private $ProfilePicture;
private $ProfilePictureID;
function __construct($DB_con, $ID, $Fname, $Srname, $Email, $Level, $FolderPath, $LastLogin, $LastIP, $Gender, $Birth, $DisplayName, $ProfilePicture, $ProfilePictureID){
$BirthDay = strtotime($Birth);
$this->DB = $DB_con;
$this->ID = $ID;
$this->Firstname = $Fname;
$this->Surname = $Srname;
$this->Gender = $Gender;
$this->Birth = date("d-m-Y", $BirthDay);
$this->Email = $Email;
$this->Level = $Level;
$this->FolderPath = $FolderPath;
$this->LastLogin = $LastLogin;
$this->LastIP = $LastIP;
$this->LevelWord = $this->sayLevel($Level);
$this->DisplayName = $DisplayName;
$this->ProfilePicture = $ProfilePicture;
$this->ProfilePictureID = $ProfilePictureID;
}
//Function for calling "private" data
public function show($atribut){
return $this->$atribut;
}
This object in $logged_user is beeing created in this object $user which works for registration and stuff for trying things as annonymous:
class USER
{
private $DB;
function __construct($DB_con)
{
$this->DB = $DB_con;
}
//Function for creating LOGGED_USER
public function useFactory($id){
require_once "logged_user.php";
$sql = $this->DB->prepare("SELECT us.ID, us.Firstname, us.Surname, us.Email, us.Level, us.Gender, us.Email, us.DisplayName, us.Birth, um.FolderHash, um.LastLogin, um.LastIP, uc.ProfilePictureID, up.Name, up.ID FROM Users AS us JOIN UsersMeta AS um ON us.ID = um.UsersID JOIN UsersConfig AS uc ON us.ID = uc.UsersID JOIN UsersPictures AS up ON up.ID = uc.ProfilePictureID WHERE us.ID = :id LIMIT 1");
$sql->execute(array(':id' => $id));
$sqlResult = $sql->fetchAll(PDO::FETCH_ASSOC);
if(!empty($sqlResult)){
foreach($sqlResult as $data){
return new LOGGED_USER($this->DB, $id, $data["Firstname"], $data["Surname"], $data["Email"], $data["Level"], $data["FolderHash"], $data["LastLogin"], $data["LastIP"], $data["Gender"], $data["Birth"], $data["DisplayName"], $data["Name"], $data["ID"]);
}
}else{
return "Prázdno!";
}
}
And here I am creating the $logged_userand trying to call function show():
session_start();
require_once "../config.php";
require_once "../objects/user.php";
$userFactory = new USER($db);
$userFactory->is_loggedin();
$logged_user = $userFactory->useFactory($_SESSION["user_session"]); //Returns new class (LOGGED_USER)
echo $logged_user->show("Email");

There is no need to fetchAll in your factory, as your criteria are id (the result always should be zero or one records). If you have no user with such id return null, so replace this:
$sqlResult = $sql->fetchAll(PDO::FETCH_ASSOC);
if(!empty($sqlResult)){
foreach($sqlResult as $data){
return new LOGGED_USER($this->DB, $id, $data["Firstname"], $data["Surname"], $data["Email"], $data["Level"], $data["FolderHash"], $data["LastLogin"], $data["LastIP"], $data["Gender"], $data["Birth"], $data["DisplayName"], $data["Name"], $data["ID"]);
}
}else{
return "Prázdno!";
}
with this:
$data = $sql->fetch(PDO::FETCH_ASSOC);
if (empty($data)) {
return null;
}
return new LOGGED_USER(
$this->DB,
$id, $data["Firstname"],
$data["Surname"],
$data["Email"],
$data["Level"],
$data["FolderHash"],
$data["LastLogin"],
$data["LastIP"],
$data["Gender"],
$data["Birth"],
$data["DisplayName"],
$data["Name"],
$data["ID"]
);
Then in your code check if logged_user is null:
if ($logged_user = $userFactory->useFactory($_SESSION["user_session"])) {
echo $logged_user->show("Email");
}

Related

session store only one item in array

I'm a new in php, I have a sign up form and I want to store users registered in an array or JSON,
I built user class and when I register a new user I want to add it into this array or JSON, but session array accept only one user in it and when I adding new user session removing the old one and store the new one!
This is my code:
class User
{
private $id;
private $first_name;
private $last_name;
private $email;
private $password;
public function register($id, $firstName, $lastName, $email, $password)
{
$this->id = $id;
$this->first_name = stripslashes($firstName);
$this->last_name = stripslashes($lastName);
$this->email = $email;
$this->password = password_hash($password, PASSWORD_DEFAULT);
}
}
class DB
{
public $users;
public function __construct()
{
$this->users = [];
}
}
<?php
$counter = 0;
$_SESSION['usersDB'] = new DB;
if (isset($_POST['submit'])) {
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$user = new User;
$user->register(++$counter, $firstName, $lastName, $email, $password);
array_push($_SESSION['usersDB']->users, $user);
}
echo '<pre>';
var_dump($_SESSION['usersDB']);
echo '</pre>';
?>
What I should do to sole this and store all users in one place?
You're replacing the session variable with new DB each time you run the script. You shouldn't do that if the session variable is already set.
if (!isset($_SESSION['userdDB'])) {
$_SESSION['usersDB'] = new DB;
}
Also, $counter will always be 1, since you're setting $counter = 0; at the beginning of the script. You could save this in a session variable, but there isn't really a need. You can just use:
$counter = count($_SESSION['usersDB']->users);
I'm not really sure this will do what you really want. Every browser session has its own session variables, so each user will just have a list of users that they have registered. Session variables are also temporary, so it's not a good way to keep a permanent list of registered users.
The right way to keep a permanent list of users is in a database on the server.
using cookies with serialize and unserialize function
user.php
<?php
class User
{
public static $cnt = 0;
private $id;
private $name;
public function __construct($name='')
{
self::$cnt++;
$this->id = self::$cnt;
$this->name = stripslashes($name);
}
public function __get($name){
return $this->$name;
}
public function __set($name,$val){
$this->$name = stripslashes($val);
}
public function __toString(){
return 'user('.$this->id.", ".$this->name.")";
}
}
?>
db.php
<?php
class DB
{
public $users = [];
public function __construct()
{
$this->users = [];
}
public function __toString()
{
$str = "<ul>";
foreach ($this->users as $user)
$str .="<li>".$user."</li>";
$str .= "</ul>";
return $str;
}
}
?>
index.php
<?php
require_once('user.php');
$user1 = new User('Steve');
$user2 = new User('Everst');
require_once('db.php');
$databse = new DB();
$databse->users[] = $user1;
$databse->users[] = $user2;
setcookie('users', serialize($databse),time() + 3600,"/","",0);
echo $_COOKIE['users'];
?>
users.php
<?php
require_once('db.php');
require_once('user.php');
$databse = unserialize($_COOKIE['users']);
echo $databse;
?>
using session with JSON
implements the interface JsonSerializable
override the method jsonSerialize
user.php
<?php
class User implements JsonSerializable
{
public static $cnt = 0;
private $id;
private $name;
public function __construct($name='')
{
self::$cnt++;
$this->id = self::$cnt;
$this->name = stripslashes($name);
}
public function __get($name){
return $this->$name;
}
public function __set($name,$val){
$this->$name = stripslashes($val);
}
public function __toString(){
return 'user('.$this->id.", ".$this->name.")";
}
public function jsonSerialize() {
return array(
'id' => $this->id,
'name' => $this->name
);
}
}
?>
index.php
<?php
session_start();
include('user.php');
include('db.php');
$user1 = new User('Steve');
$user2 = new User('Everst');
$databse = new DB();
$databse->users[] = $user1;
$databse->users[] = $user2;
$_SESSION['database'] = JSON_encode($databse);//{"users":[{"id":1,"name":"Steve"},{"id":2,"name":"Everst"}]}
?>
users.php
<?php
session_start();
$databse = json_decode($_SESSION['database']);
foreach ($databse->users as $user)
echo $user->id." - ".$user->name."<BR>";
?>

Can't add data from php array to json database

I have got problem with array. When i add string to json_encode it save in db but $object give me [{},{},{}]Can you tell me guys what i am doing wrong?
$objects = array();
$objects[] = new Person(1, 'John', 'Smith','java');
$objects[] = new Person(2, 'Stacy', 'Smith','php');
$Db ='./DB.json';
$saveInBase = json_encode($objects);
file_put_contents($Db, $saveInBase);
$loadFromBase = file_get_contents($Db);
$loadFromBase = json_decode($loadFromBase, true);
Please implement JsonSerializable on Person class, you only will have to implement jsonSerialize method, here you have an example:
<?php
class Person implements JsonSerializable
{
private $id;
private $name;
private $last_name;
private $lang;
public function __construct($id, $name, $last_name, $lang)
{
$this->id = $id;
$this->name = $name;
$this->last_name = $last_name;
$this->lang = $lang;
}
public function jsonSerialize()
{
return get_object_vars($this);
}
}
$objects = array();
$objects[] = new Person(1, 'John', 'Smith','java');
$objects[] = new Person(2, 'Stacy', 'Smith','php');
$Db ='./DB.json';
$saveInBase = json_encode($objects);
file_put_contents($Db, $saveInBase);
$loadFromBase = file_get_contents($Db);
$loadFromBase = json_decode($loadFromBase, true);

Trying to get property of non-object using php oops concept

I am trying to retrieve the data from database using OO-PHP
Here is my code
user.php
<?php
require_once("init.php");
class User{
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public static function find_all_users(){
return self::find_this_query("SELECT * FROM users");
}
public static function find_user_by_id($user_id){
global $database;
/* $result_set = $database->query("SELECT * FROM users WHERE id=$user_id LIMIT 1");*/
$result_set = self::find_this_query("SELECT * FROM users WHERE id=$user_id LIMIT 1");
$found_user = mysqli_fetch_array($result_set);
return $found_user;
}
public static function find_this_query($sql){
global $database;
$result_set = $database->query($sql);
$the_object_array = array();
while($row = mysqli_fetch_array($result_set)){
$the_object_array[] = self::instantation($row);
}
return $result_set;
}
public static function instantation($the_record){
$the_object = new self;
/* $the_object->id = $found_user['id'];
$the_object->username = $found_user['username'];
$the_object->password = $found_user['password'];
$the_object->first_name = $found_user['first_name'];
$the_object->last_name = $found_user['last_name'];*/
foreach($the_record as $the_attribute => $value){
if($the_object->has_the_attribute($the_attribute)){
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
private function has_the_attribute($the_attribute){
$object_properties = get_object_vars($this);
return array_key_exists($the_attribute, $object_properties);
}
}
?>
database.php
public function query($sql){
/*$result = mysqli_query($this->connection,$sql);*/
$result = $this->connection->query($sql);
$this->confirm_query($result);
return $result;
}
index.php
$users = User::find_all_users();
foreach($users as $user){
echo $user->username;
}
When trying to retrieve the users from the database I get the error
Trying to get property of non-object
The problem is, you are not returning the users array from this method
public static function find_this_query($sql){
global $database;
$result_set = $database->query($sql);
$the_object_array = array();
while($row = mysqli_fetch_array($result_set)){
$the_object_array[] = self::instantation($row);
}
return $result_set;
}
instead you should return the array as
public static function find_this_query($sql){
global $database;
$result_set = $database->query($sql);
$the_object_array = array();
while($row = mysqli_fetch_array($result_set)){
$the_object_array[] = self::instantation($row);
}
return $the_object_array;
}
and just in case the result is empty, check for it as
$users = User::find_all_users();
if($users != null){
foreach($users as $user){
echo $user->username;
}
}

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 - Using classes to fetch user info

Assume the connection to the database and all references to tables and cells is correct... how could I get something like this working?
class User
{
private $_display;
private $_email;
public function __construct($username)
{
$fetch_user = mysql_query("SELECT * FROM `registered_users` WHERE `user_name`='$username'");
$fetch_user = mysql_fetch_array($fetch_user);
$this->_display = $fetch_user['user_display'];
$this->_email = $fetch_user['user_email'];
}
}
$person1 = new User('username');
echo "Information: " . print_r($person1, TRUE);
the problem is it returns nothing. Doesn't thrown an error or anything when debugged. Is it viable method though? :S
Here is roughly what I would do:
<?php
class User{
private $username;
private $data;
public function __construct($username){
$this->username = $username;
if($this->valid_username()){
$this->load();
}
}
private function load(){
// Let's pretend you have a global $db object.
global $db;
$this->data = $db->query('SELECT * FROM registered_users WHERE user_name=:username', array(':username'=>$this->username))->execute()->fetchAll();
}
public function save(){
// Save $this->data here.
}
/**
* PHP Magic Getter
*/
public function __get($var){
return $this->data[$var];
}
/**
* PHP Magic Setter
*/
public function __set($var, $val){
$this->data[$var] = $val;
}
private function valid_username(){
//check $this->username for validness.
}
// This lets you use the object as a string.
public function __toString(){
return $this->data['user_name'];
}
}
How to use:
<?php
$user = new User('donutdan');
echo $user->name; //will echo 'dan'
$user->name = 'bob';
$user->save(); // will save 'bob' to the database

Categories