Can't add data from php array to json database - php

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);

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>";
?>

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

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");
}

return class properties as JSON

I'm trying to encode some properties in a class in php to JSON but all my method is returning is {}
Here's my code, where am I going wrong?
Thanks.
<?php
class Person
{
private $_photo;
private $_name;
private $_email;
public function __construct($photo, $name, $email)
{
$this->_photo = $photo;
$this->_name = $name;
$this->_email = $email;
}
public function getJsonData() {
$json = new stdClass;
foreach (get_object_vars($this) as $name => $value) {
$this->$name = $value;
}
return json_encode($json);
}
}
$person1 = new Person("mypicture.jpg", "john doe", "doeman#gmail.com");
print_r( $person1->getJsonData() );
That's is because you are not using the $json variable but instead you are using $this->$name. Which $this are you refering too? You aren't using the $json variable from what I am seeing.
class Person
{
private $_photo;
private $_name;
private $_email;
public function __construct($photo, $name, $email)
{
$this->_photo = $photo;
$this->_name = $name;
$this->_email = $email;
}
public function getJsonData() {
//I'd make this an array
//$json = new stdClass;
$json = array();
foreach (get_object_vars($this) as $name => $value) {
//Here is my change
//$this->$name = $value;
$json[$name] = $value
}
return json_encode($json);
}
}
$person1 = new Person("mypicture.jpg", "john doe", "doeman#gmail.com");
print_r( $person1->getJsonData() );
Hope it solves you problem. That's how I would do it.
Implement the JsonSerializable interface in your class, starting with PHP 5.4.

PHP: How to use dynamic variable name with a class' setter

I have a class with a private member "description" but that proposes a setter :
class Foo {
private $description;
public function setDescription($description) {
$this->description = $description;
}
}
I have the name of the member in a variable. I would like to access the field dynamically. If the field was simply public I could do :
$bar = "description";
$f = new Foo();
$f->$bar = "asdf";
but I don't know how to do in the case I have only a setter.
<?php
$bar = "description";
$f = new Foo();
$func="set"+ucwords($bar);
$f->$func("asdf");
?>
Try this:
$bar = 'description';
$f = new Foo();
$f->{'set'.ucwords($bar)}('test');
This function come do the job:
private function bindEntityValues(Product $entity, array $data) {
foreach ($data as $key => $value){
$funcName = 'set'+ucwords($key);
if(method_exists($entity, $funcName)) $entity->$funcName($value);
}
}
Use magic setter
class Foo {
private $description;
function __set($name,$value)
{
$this->$name = $value;
}
/*public function setDescription($description) {
$this->description = $description;
}*/
}
but by this way your all private properties will act as public ones if you want it for just description use this
class Foo {
private $description;
function __set($name,$value)
{
if($name == 'description')
{ $this->$name = $value;
return true;
}
else
return false
}
/*public function setDescription($description) {
$this->description = $description;
}*/
}

PHP OOP: Iterate over all objects created from a class

I want to create a <select> field from all Gender objects. Is there a way to iterate over all the objects created from the class of Gender?
class Gender {
public static $counter = 0;
public $id;
public $gender;
public function __construct($gender){
Gender::$counter++;
$this->id = Gender::$counter;
$this->gender = $gender;
}
}
// Objects
$gender_male = new Gender('Male');
$gender_female = new Gender('Female');
Is there a way to iterate over all the objects created from the class of Gender?
To a degree, yes, but it's a very bad idea design-wise.
Why not put all the relevant objects you want to query into an array?
$genders = array();
$genders["male"] = new Gender('Male');
$genders["female"] = new Gender('Female');
you can then walk through each element using
foreach ($genders as $gender)
echo $gender->id;
Something like this you could do.
class Gender {
public static $genders = array();
public $gender;
public function __construct($gender){
$this->gender = $gender;
self::genders[] = $this;
}
}
// Objects
$gender_male = new Gender('Male');
$gender_female = new Gender('Female');
foreach(Gender::genders as $gender) {
...
}
This is my solution:
$_genders = array('Male','Female','Alien');
$gender = array();
foreach($_genders as $g)
{
$gender[$g] = new Gender($g);
}
Maybe a Container-Class would fit perfect for this task.
Take a look to: SplObjectStorage
class Gender {
public static $counter = 0;
public $id;
public $gender;
private static $instances = array();
public function __construct($gender){
Gender::$counter++;
$this->id = Gender::$counter;
$this->gender = $gender;
self::$instances[] = $this;
}
public static function getInstances(){
return self::$instances;
}
}
new Gender( "male" );
new Gender( "male" );
foreach( Gender::getInstances() as $genderInstance ) {
echo $genderInstance->gender;
}
I understand now that it's an extreme overkill to use a class but for the sake of knowing how it's done, here's the new code (based on all your comments):
class Gender {
public static $counter = 0;
public static $genders = array();
public function __construct($gender){
// Here it is
Gender::$genders[++Gender::$counter] = $gender;
}
}
// Objects
$gender_male = new Gender('Male');
$gender_female = new Gender('Female');
It's a group achievement in its own way but I think I'll switch to arrays instead. :-)

Categories