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

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

Related

How to dynamically display user name from the database after log in?

I need to dynamically display user name from logged in user in my OOP PHP project. I can display it when I type right id from the database but it shows error when I try to define property $user_id in my function find_by_id. I need help on how to define $user_id variable. Here is my code:
index.php
<?php $user = User::find_by_id($user_id); ?>
<h1>Hello, <?php echo $user->username; ?></h1>
user.php
<?php
class User
{
protected static $db_table = "users";
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
private function has_the_attribute($the_attribute)
{
$object_properties = get_object_vars($this);
return array_key_exists($the_attribute, $object_properties);
}
public static function instantation($the_record)
{
$the_object = new self;
foreach ($the_record as $the_attribute => $value) {
if ($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
public static function find_this_query($sql)
{
global $database;
$result_set = $database->query($sql);
$the_object_array = [];
while ($row = mysqli_fetch_array($result_set)) {
$the_object_array[] = self::instantation($row);
}
return $the_object_array;
}
public static function find_all()
{
return self::find_this_query("SELECT * FROM " . static::$db_table . " ");
}
public static function find_by_id($user_id)
{
global $database;
$the_result_array = self::find_this_query("SELECT * FROM " . self::$db_table . " WHERE id = $user_id");
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
public static function verify_user($username, $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$sql = "SELECT * FROM " . self::$db_table . " WHERE ";
$sql .= "username = '{$username}' ";
$sql .= "AND password = '{$password}'";
$the_result_array = self::find_this_query($sql);
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
}
$user = new User();
session.php
<?php
class Session
{
private $signed_in = false;
public $user_id;
public $message;
public function __construct()
{
session_start();
$this->check_the_login();
$this->check_message();
}
public function login($user)
{
if ($user) {
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->signed_in = true;
}
}
public function logout()
{
unset($_SESSION['user_id']);
unset($this->user_id);
$this->signed_in = false;
}
private function check_the_login()
{
if (isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->signed_in = true;
} else {
unset($this->user_id);
$this->signed_in = false;
}
}
public function is_signed_in()
{
return $this->signed_in;
}
public function message($msg="")
{
if (!empty($msg)) {
$_SESSION['message'] = $msg;
} else {
return $this->message;
}
}
public function check_message()
{
if (isset($_SESSION['message'])) {
$this->message = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$this->message = "";
}
}
}
$session = new Session();
For the sake of marking this as accepted, what you need to do is actually pass the user ID of the and not just an uninitialised variable, if your instance you are storing it in the session so I presume it would be:
<?php $user = User::find_by_id($_SESSION['user_id']); ?>
Note: To make your templating cleaner, you can use the shorthand syntax for echo:
<h1>Hello, <?= $user->username; ?></h1>
Another thing to note is that you have built a Session class, however you are still for some reason accessing the data through $_SESSION which doesn't make sense, make some setters / getters for it. Finally, sessions are something that you'll be using a lot therefore it would be worth making that class static.
Reading Material
echo

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';
}

OOP returning variables

Hello I am new to OOP and I have a class with a method and I am trying to return a variable to the class from a method but I am obviously missing something...
Here is my Class:
class Certification {
public $uid;
public $men_id;
public $sm_id;
public $sm_rec;
public $three_days;
public $min_on_test;
public $signed;
public $mid_year;
public $police_check;
public $io_comments;
public $date_certified;
public function __construct($uid)
{
include 'conn.php';
$stmt = $conn->prepare(
'SELECT * FROM certification WHERE uid = :uid');
$stmt->execute(array(':uid' => $uid));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$this->uid = $row['uid'];
$this->nid = $row['nid'];
$this->nid = $row['date_certified'];
$this->men_id = $row['men_id'];
$this->sm_id = $row['sm_id'];
$this->sm_rec = $row['sm_rec'];
$this->three_days = $row['three_days'];
$this->min_on_test = $row['min_on_test'];
$this->signed = $row['signed'];
//$this->mid_year = $row['mid_year'];
$this->police_check = $row['police_check'];
$this->io_comments = $row['io_comments'];
}
}
public function get_mid_year ($uid) {
include 'conn.php';
$stmt = $conn->prepare(
'SELECT courseReviewed FROM vti_users WHERE uid = :uid');
$stmt->execute(array(':uid' => $uid));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$this->mid_year = $row['courseReviewed'];
return $this->mid_year;
}
}
}
I thought that this method would return the $mid_year variable to the class but is null when I use var_dump().
Any advice about correcting my flawed logic would be a great help for a beginner.

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.

Categories