Not getting desired output from PHP class - php

This is my very first question actually. I am under a learning process of OOP PHP and trying to design my first class for Category. Here is my code
<?php
class category{
public $catid;
public $datacol;
public function __construct($catid=0)
{
$this->catid=0;
$this->datacol=$this->load($catid);
}
public function load($catid)
{
global $conn;
$sql=' select * '
.' FROM tbl_categories'
.' WHERE catid='.$catid;
if (!($res=mysqli_query($conn,$sql)) || !mysqli_num_rows($res)>0)
return false;
$this->datacol = mysqli_fetch_array($res);
$this->catid = $this->datacol['catid'];
return true;
}
public function reload() {
return $this->load($this->getId());
}
/* ------------------> Getter methods <--------------------- */
public function getId() { return $this->catid; }
public function getName() { return $this->datacol['category']; }
public function getOneliner() { return $this->datacol['categoryoneliner']; }
public function getBrief() { return $this->datacol['categorybrief']; }
public function getThumb() { return $this->datacol['timg']; }
public function getImage() { return $this->datacol['limg']; }
public function getParentID() { return $this->datacol['parentcat']; }
public function getPagetitle() { return $this->datacol['catpagetitle']; }
public function getKeywords() { return $this->datacol['catkeywords']; }
public function getMetadesc() { return $this->datacol['categorymetadesc']; }
public function getPriority() { return $this->datacol['priority']; }
public function getRemarks() { return ($this->datacol['remarks']); }
public function getRow() { return $this->datacol; }
}
?>
Now,
When i create its object from other file with a code as below:
$cat=new category(10);
echo var_dump($cat);
echo var_dump($cat->getId());
echo var_dump($cat->getName());
The output gives me the correct catid when called getID(). But Shows NULL for getName() or any other function other than getID().
What am i doing wrong?
Thanks in advance

As #Arnold Gandarillas said, you are overwriting $datacol in the constructor.
Your constructor calls load(), which sets $datacol:
public function load($catid)
{
...
$this->datacol = mysqli_fetch_array($res);
return true;
}
The function then returns true. In the constructor, this true is assigned to $datacol, overwriting the previous value:
public function __construct($catid=0)
{
$this->catid=0;
$this->datacol=$this->load($catid);
}
Change the constructor to something like this:
public function __construct($catid=0)
{
if ($catid > 0)
$this->load($catid);
}

Alright - look closely to your function:
public function load($catid)
{
global $conn;
$sql=' select * '
.' FROM tbl_categories'
.' WHERE catid='.$catid;
if (!($res=mysqli_query($conn,$sql)) || !mysqli_num_rows($res)>0)
return false;
$this->datacol = mysqli_fetch_array($res);
$this->catid = $this->datacol['catid'];
return true;
}
So, you function returns either true of false. And this boolean values is assgined to $this->datacol here:
$this->datacol = $this->load($catid);
As this assignment happens after you did $this->datacol = mysqli_fetch_array($res);, your $this->datacol becomes either true or false, and holds no real data from mysql.
So, one of the solutions can be to remove assignment:
public function __construct($catid=0)
{
$this->catid=0;
$this->load($catid);
}
In this case your $this->datacol is not overwritten.

its simple $this->datacol = $this->load($catid); is not required
you have assigning $this->datacol twice
public function __construct($catid=0)
{
$this->catid=0;
$this->load($catid);
}
public function load($catid)
{
global $conn;
$sql=' select * '
.' FROM tbl_categories'
.' WHERE catid='.$catid;
if (!($res=mysqli_query($conn,$sql)) || !mysqli_num_rows($res)>0)
return false;
$this->datacol = mysqli_fetch_array($res);
$this->catid = $this->datacol['catid'];
return true;
}
please add if anything is missing

Related

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

Codeigniter comparison input with database?

I try to comparise string from input to string in database.
This is my code:
Controller:
public function __construct() {
parent::__construct();
$this->captcha_rejestracja = rand(1,40);
}
public function register() {
$str = $this->input->post('captcharejestr');
$this->form_validation->set_rules('captcharejestr', 'kod z obrazka', 'trim|required|alpha_numeric|xss_clean|callback_captcha_check[$str]');
}
public function captcha_check($str) {
$jakacaptcha = $this->captcha_rejestracja;
$this->load->model('Tresci');
if ($str != $this->Tresci->captcha($jakacaptcha))
{
$this->form_validation->set_message('captcha_check', 'Błędnie przepisany kod z obrazka.');
return FALSE;
}
else
{
return TRUE;
}
}
Model:
public function captcha($jakacaptcha) {
$query = $this->db->query('SELECT kod FROM captcha WHERE numer='.$jakacaptcha.'');
$row = $query->row_array();
return $row['kod'];
}
I dont know where is the problem because everytime i have return FALSE from my callback ??
You don't seem to be running the form validation.
public function __construct()
{
parent::__construct();
// this is somewhat confusing, why randon value ?
// the database query should have one value :-/
$this->captcha_rejestracja = rand(1,40);
$this->load->model('Tresci');
}
public function register()
{
$this->form_validation->set_rules('field', 'label', 'callback_captcha_check' );
if(!$this->form_validation->run()){
//show the form again
return;
}
//create a new user
}
public function captcha_check($str)
{
$this->form_validation->set_message('captcha_check', 'Message here...');
$result = $this->tresci->captcha($this->captcha_rejestracja);
return ( $str == (string)$result ) ? true : false;
}

How can I implement Method Chaining in PHP 5.x?

I have the following class written for PHP 5.4.x. Should this work as I expect?
class SqlBuilder {
private $dbTable;
private $action;
private $data;
private $clause;
public function toString() {
// $sql = generate sql string
// [...]
return $sql;
}
[...]
public function setClause($clause) {
$this->clause = $clause;
}
public function setDbTable($dbTable) {
$this->dbTable = $dbTable;
}
public function setAction($action) {
$this->action = $action;
}
}
$sql = (new \dbal\SqlBuilder())
->setAction($this->action)
->setClause($this->clause)
->setDbTable($this->dbTable)
->toString();
I am expecting to be able to access all of my setter methods. Instead I see the following error:
Fatal error: Call to a member function toString() on a non-object )
This seems to work:
$builder= new \dbal\SqlBuilder();
$builder->setAction($this->action)
$builder->setClause($this->clause)
$builder->setDbTable($this->dbTable)
$sql = $builder->toString();
But I know that this works as well:
class Foo
{
public $a = "I'm a!";
public $b = "I'm b!";
public $c;
public function getB() {
return $this->b;
}
public function setC($c) {
$this->c = $c;
return $this;
}
public function getC() {
return $this->c;
}
}
print (new Foo)
->setC($_GET["c"])
->getC(); // I'm c!
I've used this style of syntax in Javascript before. Is there a way to make it work in PHP?
What you are asking about is called method chaining. In order for it to work the way you want, each method call needs to return a reference to the object that you are calling. So,
->setAction($this->action)
// needs to return $this; so that
->setClause($this->clause)
// knows what to operate upon and in turn needs to return $this; so that
->setDbTable($this->dbTable)
// can do the same
Try :
public function setClause($clause) {
$this->clause = $clause;
return $this;
}
public function setDbTable($dbTable) {
$this->dbTable = $dbTable;
return $this;
}
public function setAction($action) {
$this->action = $action;
return $this;
}

PHP method chaining

Can anyone explain me why this code does not work (the content $this->_string) is empty?
<?php
class WordProcessor
{
public $_string = '';
public function __constructor($text)
{
$this->_string = $text;
}
public function toLowerCase()
{
$this->_string = strtolower($this->_string);
return $this;
}
public function trimString()
{
echo $this->_string;
$this->_string = trim($this->_string);
return $this;
}
public function capitalizeFirstLetter()
{
$this->_string = trim($this->_string);
return $this;
}
public function printResult()
{
echo $this->_string;
}
}
$data = new WordProcessor("here Are some words! ");
$data->trimString()->toLowerCase()->capitalizeFirstLetter()->printResult();
Use construct instead of constructor?
Its
public function __construct($text)
not __constructor(..)

How perform USort() on an Array of Objects class definition as a method?

class Contact{
public $name;
public $bgcolor;
public $lgcolor;
public $email;
public $element;
public function __construct($name, $bgcolor, $lgcolor, $email, $element)
{
$this->name = $name;
$this->bgcolor = $bgcolor;
$this->lgcolor = $lgcolor;
$this->email = $email;
$this->element = $element;
}
public static function sortByName(Contact $p1, Contact $p2)
{
return strcmp($p1->name, $p2->name);
}
}
class ContactList implements Iterator, ArrayAccess
{
protected $_label;
protected $_contacts = array();
public function __construct($label)
{
$this->_label = $label;
}
public function getLabel()
{
return $this->_label;
}
public function addContact(Contact $contact)
{
$this->_contacts[] = $contact;
}
public function current()
{
return current($this->_contacts);
}
public function key()
{
return key($this->_contacts);
}
public function next()
{
return next($this->_contacts);
}
public function rewind()
{
return reset($this->_contacts);
}
public function valid()
{
return current($this->_contacts);
}
public function offsetGet($offset)
{
return $this->_contacts[$offset];
}
public function offsetSet($offset, $data)
{
if (!$data instanceof Contact)
throw new InvalidArgumentException('Only Contact objects allowed in a ContactList');
if ($offset == '')
{
$this->_contacts[] = $data;
} else
{
$this->_contacts[$offset] = $data;
}
}
public function offsetUnset($offset)
{
unset($this->_contacts[$offset]);
}
public function offsetExists($offset) {
return isset($this->_contacts[$offset]);
}
public function sort($attribute = 'name')
{
$sortFct = 'sortBy' . ucfirst(strtolower($attribute));
if (!in_array($sortFct, get_class_methods('Contact')))
{
throw new Exception('contact->sort(): Can\'t sort by ' . $attribute);
}
usort($this->contact, 'ContactList::' . $sortFct);
}
}
public function Sort($property, $asc=true)
{
// this is where sorting logic takes place
$_pd = $this->_contact->getProperty($property);
if ($_pd == null)
{
user_error('Property '.$property.' does not exist in class '.$this->_contact->getName(), E_WARNING);
return;
}
// set sortDescriptor
ContactList::$sortProperty = $_pd;
// and apply sorting
usort($this->_array, array('ContactList', ($asc?'USortAsc':'USortDesc')));
}
function getItems(){
return $this->_array;
}
class SortableItem extends ContactList
{
static public $sortProperty;
static function USortAsc($a, $b)
{
/*#var $_pd ReflectionProperty*/
/*
$_pd = self::$sortProperty;
if ($_pd !== null)
{
if ($_pd->getValue($a) === $_pd->getValue($b))
return 0;
else
return (($_pd->getValue($a) < $_pd->getValue($b))?-1:1);
}
return 0;
}
static function USortDesc($a, $b)
{
return -(self::USortAsc($a,$b));
}
}
This approach keeps giving me PHP Warnings: usort() [function.usort]: of all kinds which I can provide later as needed to comment out those methods and definitions in order to test and fix some minor bugs of our program.
**$billy parameters are already defined.
$all -> addContact($billy);
// --> ended up adding each contact manually above
$all->Sort('name',true);
$items = $all->getItems();
foreach($items as $contact)
{
echo $contact->__toString();
}
$all->sort();
The reason for using usort is to re-arrange the order alphabetically by name but somehow is either stating that the function comparison needs to be an array or another errors which obviously I have seemed to pass. Any help would be greatly appreciated, thanks in advance.
It's happening because the variable inside the usort call is not a valid array. You use $this->_contacts everywhere, but your usort line is:
usort($this->contact, 'ContactList::' . $sortFct);
Try changing that to:
usort($this->_contacts, 'ContactList::' . $sortFct);
<?php
class Contact{
public $name;
public $bgcolor;
public $lgcolor;
public $email;
public $element;
public function __construct($name, $bgcolor, $lgcolor, $email, $element)
{
$this->name = $name;
$this->bgcolor = $bgcolor;
$this->lgcolor = $lgcolor;
$this->email = $email;
$this->element = $element;
}
}
class ContactList implements Iterator, ArrayAccess
{
public $_label;
public $_contacts = array();
public function __construct($label)
{
$this->_label = $label;
}
public function getLabel()
{
return $this->_label;
}
public function addContact(Contact $contact)
{
$this->_contacts[] = $contact;
}
public function current()
{
return current($this->_contacts);
}
public function key()
{
return key($this->_contacts);
}
public function next()
{
return next($this->_contacts);
}
public function rewind()
{
return reset($this->_contacts);
}
public function valid()
{
return current($this->_contacts);
}
public function offsetGet($offset)
{
return $this->_contacts[$offset];
}
public function offsetSet($offset, $data)
{
if (!$data instanceof Contact)
throw new InvalidArgumentException('Only Contact objects allowed in a ContactList');
if ($offset == '')
{
$this->_contacts[] = $data;
} else
{
$this->_contacts[$offset] = $data;
}
}
public function offsetUnset($offset)
{
unset($this->_contacts[$offset]);
}
public function offsetExists($offset) {
return isset($this->_contacts[$offset]);
}
/* This is the comparing function to be used with usort to make it alphabetically ordered for All Contacts */
public function sort_by($field, &$arr, $sorting='SORT_DSC', $case_insensitive=true){
if(is_array($arr) && (count($arr)>0) && ( ( is_array($arr[0]) && isset($arr[0][$field]) ) || ( is_object($arr[0]) && isset($arr[0]->$field) ) ) ){
if($case_insensitive==true) $strcmp_fn = "strnatcasecmp";
else $strcmp_fn = "strnatcmp";
if($sorting=='SORT_DSC'){
$fn = create_function('$a,$b', '
if(is_object($a) && is_object($b)){
return '.$strcmp_fn.'($a->'.$field.', $b->'.$field.');
}else if(is_array($a) && is_array($b)){
return '.$strcmp_fn.'($a["'.$field.'"], $b["'.$field.'"]);
}else return 0;
');
}else if($sorting=='SORT_ASC'){
$fn = create_function('$a,$b', '
if(is_object($a) && is_object($b)){
return '.$strcmp_fn.'($b->'.$field.', $a->'.$field.');
}else if(is_array($a) && is_array($b)){
return '.$strcmp_fn.'($b["'.$field.'"], $a["'.$field.'"]);
}else return 0;
');
}
usort($arr, $fn);
return true;
}else{
return false;
}
}
}
?
The call:
$all->sort_by('name',$all->_contacts,'SORT_DSC','false');

Categories