Fetch all results with OOP Php - php

I've been following a tutorial about oop php on youtube. He made a method to fetch only the first result of a query. I tried to grab all results, but I get a warning message : Trying to get property of non-object
Also when I var_dump(); my object holding the result (which I assumed), it returns null.
What am I doing wrong?
This is the full code:
DB class:
class DB {
private $_results;
public function query($sql, $params = array()) {
$this->_error = false;
if ($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if (count($params)) {
foreach ($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if ($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
// First result only:
public function first() {
return $this->results()[0];
}
// All results as I thought:
public function first() {
return $this->results();
}
public function results() {
return $this->_results;
}
}
Project Class:
class Project {
private $_db,
$_data;
public function __construct() {
$this->_db = DB::getInstance();
}
public function find($user = null) {
if ($user) {
$data = $this->_db->get('user_project', array('uid', '=', $user));
if ($data->count()) {
$this->_data = $data->all();
return $this->data()->id;
}
}
}
public function data() {
return $this->_data;
}
}
I tried to access it by doing this:
$project = new Project();
var_dump($project->find($user->data()->id)); // $user->data()->id is just the id of a user

Thanks for pointing me the right direction, I've figured it out.
$this->_data = $data->results();
return $this->_data;
Then I had to loop through it. Solved.

Related

Returning data in PHP returns Null

I am storing the returned data from a query in this private $_data variable.
When I use the $ticket->find() function it is returning data.
When I use $ticket->data() it returns null.
Why would this be if they are both returning the same variable? How can I make data() return AND display the data?
<?php
class Ticket {
public $_db,
$_data;
public function __construct($ticket = null) {
$this->_db = DB::getInstance();
}
public function create($fields = array()) {
if(!$this->_db->insert('tickets', $fields)) {
throw new Exception('There was a problem creating a ticket.');
}
}
public function find() {
$data = $this->_db->get('tickets', array('uid', '=', '18'));
$this->_data = $data;
return $this->_data;
}
public function data() {
return $this->_data;
}
}

Get data return php oop

getclass.php
public $set;
//dont need to care here the code is right , here is where it final result
default;
$this->actual_device = "desktop";
echo $this->issetValueNull($this->actual_device);
public function issetValueNull($mixed)
{
$this->set = $mixed;
}
getdata.php
require_once "getclass.php";
$check_detect_device = new detect_device();
if($check_detect_device->issetValueNull->set1 = "desktop"){
"<script>console.log('desktop');</script>";
}
i need to get the data from getclass.php to getdata.php and check the final result at getdata.php , some like below;
//this data return from getclass.php
if(isset($_GET['desktop'])){
"<script>console.log('desktop');</script>";
}
but i dont know how to return the data from getclass , can any one give me some advice ?
Im not sure is this what you are trying to do, but check my example:
<?php
class getClass
{
public $actualDevice;
public function __construct()
{
$this->actualDevice = "desktop";
}
public function setActualDevice($actualDevice)
{
$this->actualDevice = $actualDevice;
return $this;
}
public function getActualDevice()
{
return $this->actualDevice;
}
public function issetActualDevice()
{
return isset($this->actualDevice);
}
}
class getData
{
public $getClass;
public function __construct(getClass $getClass)
{
$this->getClass = $getClass;
}
public function checkDetectDevice($device)
{
if ($this->getClass->getActualDevice() == $device) {
return true;
}
return false;
}
}
$getClass = new getClass();
$getData = new getData($getClass);
if ($getData->checkDetectDevice($_GET['desktop'])) {
echo "<script>console.log('desktop');</script>";
}

Fatal Error call to member function count() is non object

I am trying to query a database using pdo, but I cant figure out the problem. I have created an init file for my db details and server details and config file for configuration and index file and DB file.
index.php
<?php
require_once 'core/init.php';
$user = Db::getInstance()->get('users',array('username', '=' , 'raja' ));
if($user->count())
{
echo "No user";
}
else{
echo "OK!";
}
?>
Db.php
<?php
class Db
{
private static $_instance = null;
private $_pdo,
$_query,
$_error=false,
$_results,
$_count=0;
private function __construct()
{
try
{
$this->_pdo =new PDO("mysql:host=" .Config::get('mysql/host') . ";dbname=" .Config::get('mysql/db'),Config::get('mysql/username'),Config::get('mysql/password'));
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
public static function getInstance()
{
if (!isset(self::$_instance))
{
self::$_instance = new Db();
}
return self::$_instance;
}
public function query($sql,$params=array())
{
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql))
{
$x=1;
if (count($params))
{
foreach ($params as $param )
{
$this->_query->bindValue($x,$param);
$x++;
}
}
if ($this->_query->execute())
{
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}
else
{
$this->error=true;
}
}
return $this;
}
public function action($action,$table,$where=array())
{
if(count($where) === 3)
{
$operators = array('=','<','>','>=','<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator,$operators))
{
$sql = "{$action}FROM{$table} WHERE {$field} {$operator} ?";
if($this->query($sql,array($value))->error()){
return $this;
}
}
}
return false;
}
public function get($table,$where)
{
return $this->action('SELECT *', $table, $where);
}
public function delete($table,$where)
{
return $this->action('DELETE ', $table,$where);
}
public function error()
{
return $this->_error;
}
public function count()
{
return $this->_count;
}
}
?>
It reports a fatal error about not finding the count object:
Fatal error: Call to a member function count() on a non-object in
C:\xampp\htdocs\Student Management system\index.php on line 6
You want to declare the object -- just calling an instance from part of the object class returns just that, a non-complete object part. You're calling the function as if it's just a function rather than if it is part of the class as a whole, so then referencing any other parts of the class as a whole the logic is lost because PHP only views it as a get function alone.
To solve:
<?php
require_once 'core/init.php';
//here
$user = new Db();
$userSelect = $user->get('users',array('username', '=' , 'raja' ));
...
From this, $user is your object.
Sinlgeton
If you want to instead create the connection as a singleton, then each reference to a class method (~function) must be referenced with the singleton syntax - the reference to count() should therefore need to be rewritten into a Singleton syntax using :: instead of -> .
please read http://www.phptherightway.com/pages/Design-Patterns.html

PDO Object and Array

I have followed PHP Academy's OOP Tutorial over here
The DB class has been made in a way to fetch database results as an Object
public function query($sql, $params=array()){
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)){
$x=1;
if(count($params)){
foreach ($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}else{
$this->_error = true;
}
}
return $this;
}
This is important cause the user login is done like this
public function login($username = null, $password = null){
$user = $this->find($username);
if($user){
if($this->data()->password === Hash::make($password, $this->data()->salt)){
Session::put($this->_sessionName, $this->data()->id);
return true;
}
}
return false;
}
Now when i want to implement foreach to get results row-wise, they are asking for an Array
$result = $product->getData($_GET['id']);
if(!empty($result)){
foreach ($result as $row) {echo $row['id'];}}
getData Function
public function getData($_id){
return $this->_db->get('products', array('id', '=', $_id))->results();
}
results function is in DB class
public function results(){
return $this->_results;
}
When I change Fetch All to get Both OBJ and ARRAY, User cant log in.
What should i do? Which function to change?
Sorry for Bad English
Thanks in Advance

access $this in extended class

I've been following a tutorial about OOP programming. And I got this class named User:
class User {
private $_db,
$_data,
$_sessionName,
$_isLoggedIn;
public function __construct($user = null) {
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
if (!$user) {
if (Session::exists($this->_sessionName)) {
$user = Session::get($this->_sessionName);
if ($this->find($user)) {
$this->_isLoggedIn = true;
} else {
// Process logout
}
}
} else {
$this->find($user);
}
}
public function update($fields = array(), $id = null) {
if (!$id && $this->isLoggedIn()) {
$id = $this->data()->id;
}
if (!$this->_db->update('users', $id, $fields)) {
throw new Exception('De gegevens konden niet gewijzigd worden');
}
}
public function create($fields = array()) {
if (!$this->_db->insert('users', $fields)) {
throw new Exception('Het account is niet aangemaakt');
}
}
public function find($user = null) {
if ($user) {
$field = (is_numeric($user)) ? 'id' : 'email';
$data = $this->_db->get('users', array($field, '=', $user));
if ($data->count()) {
$this->_data = $data->first();
return true;
}
}
}
public function login($email = null, $password = null) {
$user = $this->find($email);
if ($user) {
if ($this->data()->password === hash::make($password)) {
session::put($this->_sessionName, $this->data()->id);
return true;
}
}
return false;
}
public function logout() {
session::delete($this->_sessionName);
}
public function hasPermission($key) {
$group = $this->_db->get('user_role', array('id', '=', $this->data()->rank));
if ($group->count()) {
$permissions = json_decode($group->first()->permission, true);
if ($permissions[$key] == true) {
return true;
}
}
return false;
}
public function data() {
return $this->_data;
}
public function isLoggedIn() {
return $this->_isLoggedIn;
}
}
Each user has different quicklinks stored in the database. I tried to extend the class User with class Link like this:
class Link extends User {
public static function getUserLinks($user) {
if ($user) {
$data = $this->_db->get('user_links', array('uid', '=', $user));
if ($data->count()) {
$this->_data = $data->results();
return $this->_data;
} else {
echo 'No matches found';
}
}
return false;
}
But I get an error message :
Fatal error: Using $this when not in object context in ... on line 153
I thought that when extending a class I can access all the parents details?
What am I doing wrong? Also, is my logic correct behind class Link extends User?
Thanks for the help.
you are trying to access the class pointer within a static method, that's impossible since static methods belongs to the class itself and not to the instance.
you could have a static property that will hold your instance, then you could do that like so: (You'll have to make sure you got an instance of Link)
class Link extends User {
public static $instance;
public function __construct() {
parent::__construct();
self::$instance = $this;
}
public static function getUserLinks($user) {
if (self::$instance instanceof Link && $user) {
$data = self::$instance->_db->get('user_links', array('uid', '=', $user));
if ($data->count()) {
self::$instance->_data = $data->results();
return self::$instance->_data;
} else {
echo 'No matches found';
}
}
return false;
}
}

Categories