PHP class not returning array when called - php

I have a PHP class which is supposed to return an array to where the object is instantiated. I have tried to figure out what the problem is but I can't seem to see it.
Can anyone see where I have gone wrong here or point me in the right direction?
Thanks
Here is the class (within a file called 'feeds.php.)
class updateFeed {
public function index() {
$db = JFactory::getDBO();
$query = "SELECT * FROM tweets";
$db->setQuery($query);
$result = $db->loadObject()
if(strtotime($result->date_added) <= time() - 3200) {
$this->updateTweets();
}
$query = "SELECT * FROM tweets ORDER BY tweet_date DESC LIMIT 0, 3";
$db->setQuery($query);
$results = $db->loadObjectList();
$tweet_db = array();
foreach($results as $result) {
$tweet_db[] = array(
'title' => $result->title,
'text' => $result->text,
'tweet_date' => $result->tweet_date
);
}
return $tweet_db;
}
And here is where the object is instantiated (in the index.php file):
include('feeds.php');
$tweet_dbs = new updateFeed;
print_r($tweet_dbs);
The print_r in the index file shows 'updateFeed Object ( ) '.
Thanks in advance.

You are using your class wrong. You do not call index() method.
Try this:
include('feeds.php');
// Create class instance
$instance = new updateFeed;
// Call your class instance's method
$tweet_dbs = $instance->index();
// Check result and have fun
print_r($tweet_dbs);

include('feeds.php');
$tweet_dbs = new updateFeed;
$tweets = $tweet_dbs->index();
print_r($tweets);
You missed to call the index() function..

you need to call that method using object of the class.
replace
print_r($tweet_dbs)
with
print_r($tweet_dbs->index())

Related

PHP Method in Class not returning data from database

Ok this should be fairly simple.
I have a table which contains content of 3 different textboxes the method inside my class should get the content to insert into textboxes.
Example TextBoxes (TextArea) where content should be entered.
My Method
public function LoadBoxes(){
$db = DB::getInstance();
$sql = "SELECT * FROM beta_letsgocontent";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$boxes = $stmnt->fetchAll();
foreach ($boxes as $box) {
$data[] = array('Low' => $box['boxLow'],
'Medium' => $box['BoxMedium'],
'High' => $box['BoxHigh']);
}
return $data;
}//function
Here is my table (image below) so data / content from table should get inserted into the textboxes.
So when I do a test on content.php where I call the class method as such:
require_once('../classes/class.content.php');
$boxes = new Contents();
$boxes->LoadBoxes();
var_dump($boxes);
I get the following back:
Problem
As can be seen the array keys get returned however the data from database is not matched to array keys or returned by the method...I am stumped and have no idea what I am doing wrong here?
Any suggestions where I am going wrong? Could it be that I am not connecting to database correctly?
However if it was a database connection error I believe I would have received an error
Please keep in mind im a student and still learning.
UPDATE
Connection Schema
class Db {
private static $instance = NULL;
private function __construct() {}
private function __clone() {}
public static function getInstance() {
if (!isset(self::$instance)) {
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
self::$instance = new PDO('mysql:host=localhost;dbname=beta', 'root', '', $pdo_options);
}
return self::$instance;
}
}
UPDATE 2
I just did the following on a test.php page which returned correct results.
require('connection.php');
function LoadBoxes(){
$db = DB::getInstance();
$sql = "SELECT * FROM beta_letsgocontent";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$boxes = $stmnt->fetchAll();
foreach ($boxes as $box) {
$box[] = array('Low' => $box['BoxLow'],
'Medium' => $box['BoxMedium'],
'High' => $box['BoxHigh']);
}
return $box;
}//function
print_r(LoadBoxes());
?>
2 issues primary issues;
You're returning $data from the class but not populating a variable with the returned array.
You are var dumping the object itself.
This should work;
require_once('../classes/class.content.php');
$boxes = new Contents();
$data = $boxes->LoadBoxes();
var_dump($data);

Parameters to a class constructor function

I'm trying to adapt a class of mine that handles tags for events stored in a JSON file. You can create tags, delete them, restore them, view them, etc. In the code below for this library you can see that I retrieve the array from the file during the constructor function so I use it and manipulate it throughout my classes' functions.
class tagHandler {
private $tagsFile = "/home/thomassm/public_html/functions/php/tags.json";
private $LstTags;
private $LstReturn;
function __construct() {
$this->LstTags = array();
if(!file_exists ($this->tagsFile)){
$fHND = fopen($this->tagsFile, "w");
$tmpArray = array(array("EID","EName","EColor", "EDel"));
fwrite($fHND, json_encode($tmpArray));
fclose($fHND);
}
$encodedInput = file ($this->tagsFile);
$this->LstTags = json_decode($encodedInput[0], true);
if(!$this->LstTags) $this->LstTags = array();
}
function __destruct(){
$this->update();
}
public function update(){
$this->LstTags = array_values($this->LstTags);
$fHND = fopen($this->tagsFile, "w");
fwrite($fHND, json_encode($this->LstTags));
fclose($fHND);
//empty memory region
$this->LstTags = array();
$encodedInput = file ($this->tagsFile);
$this->LstTags = json_decode($encodedInput[0], true);
}
//More functions that use the collected array here.
I am trying to adapt the class to deal with people signed up to my events. Each event has a record in my database that will store a field for an array of males who sign up and females who sign up. I wish for the constructor class to get the arrays(s) from the record so they can be manipulated like the previous class. The issue is to get the array I have to search the DB for a record with the Event ID (EID) and that will require a variable passed to the constructor function. To make things worse, this parameter has to be able to change in a loop. For example, the page listing all the events will have to use this class in a loop going through each record, so it can retrieve the array to manipulate it and then show it in a table / fullcalendar before repeating the process to get the next event. I have put the code I have so far below. Its not complete (some variables haven't been renamed to male and female, etc) and may be completely wrong, but it will give you a base to explain from.
class signupHandler {
private $LstMaleS;
private $LstFemaleS;
private $LstReturn;
function __construct($IntEID) {
$this->LstTags = array();
$StrQuery = "SELECT MaleS, FemaleS FROM tblEvents WHERE EID = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('s',$IntEID);
$statement->execute ();
$results = $statement->get_result ();
}
$this->LstTags = json_decode($encodedInput[0], true);
if(!$this->LstTags) $this->LstTags = array();
}
Thanks,
Tom
function decodeNames($StrNames){
$this->LstNames = array();
$this->LstNames = json_decode($StrNames, true);
if(!$this->LstNames) $this->LstNames = array();
$this->LstNames = array_values($this->LstNames);
}
function update(){
$this->LstNames = array_values($this->LstNames);
return json_encode($this->LstNames);
}
public function addSignUp($StrNames, $StrUsername, $StrStatus){
$this->decodeNames($StrNames);
$BlnPresent = false;
for($i = 0; $i < count($this->LstNames); $i++){
if($this->LstNames[$i][0] == $StrUsername){
$this->LstNames[$i][1] = $StrStatus;
$BlnPresent = true;
}
}
if($BlnPresent == false){
array_push($this->LstNames, array($StrUsername, $StrStatus, date("Y-m-d H:i:s")));
}
return $this->update();
}
I have decided to pass the encoded JSON array to the class each time I call a function from it. Before every function it is decoded and turned into an array and at the end it is then re-encoded and returned back to the file calling it. Now I no longer have any constructor or destruct functions.

ZF2 Between Dates

I've been unable to successfully retrieve records between two dates in Zend Framework 2.
My code looks as follows:
$select = $this->getTimeTable();
$predicate = new \Zend\Db\Sql\Where();
$select->where($predicate->between("start_date", $week_sunday_date , $satruday_date));
public function getTimeTable()
{
if (!$this->timeTable)
{
$this->timeTable = new TableGateway(
'time',
$this->getServiceLocator()->get('Zend\Db\Adapter\Adapter')
);
}
return $this->timeTable;
}
"start_date" is the column in my DB that is of type DATETIME, and $week_sunday_date , $satruday_date are both generated as follows
$week_sunday_date = date("Y-m-d\TH:i:sP",strtotime('this sunday'));
$satruday_date = date("Y-m-d\TH:i:sP",strtotime("+6 day", strtotime($week_sunday_date)));
The database connection is good and I can otherwise get data. Dumping both $week_sunday_date and $satruday_date variables above I see:
string(25) "2014-11-08T00:00:00+00:00"
string(25) "2014-11-02T00:00:00+00:00"
I've also tried several other ways of in between but ultimately the page is blank and won't load due to an error.
Seems like I need something like this:
$statement = $sql->prepareStatementForSqlObject($select);
$time_list = $statement->execute();
But not sure how to initialize $sql properly.
I think the correct syntax would be:
$select->where->between('start_date', $week_sunday_date, $saturday_date);
Oh, but since, in your case $select is an instance of TableGateway, then you probably need $select->getSql()->where->between(...).
I'm a little rusty on TableGateway, we've strayed away from using it. But I think you can do something like:
$timeTable = new TableGateway(/*...*/);
$select = $timeTable->getSql()->select();
$select->columns(array('col1', 'col2'));
$select->where->between('start_date', $week_sunday_date, $saturday_date);
$resultSet = $timeTable->selectWith($select);
var_dump($resultSet->toArray());
Note: I do not recommend always converting the result set to an array, but it's nice to be able to do this for debugging purposes.
Example not using TableGateway:
Query class:
namespace Example\Model\Sql\Select;
use Zend\Db\Sql\Select;
class Time extends Select {
public function __construct($week_sunday_date, $saturday_date) {
parent::__construct(['t' => 'Time']);
$this->columns([
'col1',
'col2',
]);
$this->where->between('start_date', $week_sunday_date, $saturday_date);
}
}
Data model: (basically a glorified array object, just holds data, no business logic)
namespace Example\Model\DataContainer;
class Time extends \ArrayObject {
protected $col1;
protected $col2;
public function exchangeArray($data) {
$this->col1 = $data['col1'];
$this->col2 = $data['col2'];
}
public function getCol1() {
return $col1;
}
public function getCol2() {
return $col2;
}
}
Controller:
namespace Example\Controller;
use Example\Model\DataContainer;
use Example\Model\Sql\Select;
use Zend\Db\ResultSet\ResultSet;
class IndexController {
public function myExampleAction() {
$request = $this->getRequest();
$sm = $this->getServiceLocator();
$query = new Select\Time($request->getQuery('sunday'), $request->getQuery('saturday'));
$resultSet = new ResultSet(ResultSet::TYPE_ARRAYOBJECT, new DataContainer\Time());
$executer = $sm->get('Executer');
$resultSet = $executer->execute($query, $resultSet);
return [
'time' => $resultSet, // loop through results in your view
];
}
}
So, we create an instance of our query class, which is set up when you call the constructor implicitly by creating a new instance of it. We pass our parameters into it. Then, we create an instance of our result set class, and we specify the array object prototype. Each row returned by our query will be populated as an instance of the array object prototype. When the result set is initialized, it will automatically call exchangeArray() with the data returned for the current row. That method populates your data container, and so the result set is populated with an array of these populated data container objects. So when you loop through the result set, each row will be represented by an instance of your array object prototype.
You will have to define your own Executer class. That's not a built-in. You will have to create it and add it to the service config, so that you can get it out of the service manager like I've done in the example.
A quick example for the $sql property as you requested at the end of your question.
You should use:
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Select;
$adapter = $this->tableGateway->getAdapter();//get connection
$sql = new Sql($adapter);
$select = $sql->select();
$select->from($this->tableGateway->getTable())->where(array('active' => '1'));
$selectString = $sql->getSqlStringForSqlObject($select);
//echo $selectString;die;//this will show the quesry string build above.
$results = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);
$resultSet = new ResultSet();
$resultSet->initialize($results);
return $resultSet->toArray();//return array(use $resultSet->current() for one row)
i hope this helps

Joomla Pagination

I have successfully implemented the pagination box in a component front end listing template. however, when i try to set the limit of listing items, it won't work, i wonder what is missed out.
in the model
var $_total = null;
/**
* Pagination object
* #var object
*/
var $_pagination = null;
function __construct(){
parent::__construct();
$mainframe = JFactory::getApplication();
// Get pagination request variables
$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
// In case limit has been changed, adjust it
$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
$this->setState('limit', $limit);
$this->setState('limitstart', $limitstart);
}
function _buildQuery(){
$query = ' SELECT * '
. ' FROM #__event '
.'Where published = 1'
;
return $query;
}
function getData() {
// if data hasn't already been obtained, load it
if (empty($this->_data)) {
$query = $this->_buildQuery();
$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
}
return $this->_data;
}
function getTotal(){
// Load the content if it doesn't already exist
if (empty($this->_total)) {
$query = $this->_buildQuery();
$this->_total = $this->_getListCount($query);
}
return $this->_total;
}
function getPagination(){
// Load the content if it doesn't already exist
if (empty($this->_pagination)) {
jimport('joomla.html.pagination');
$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
}
return $this->_pagination;
}
in the views/view.html.php (full version of this document)
class EventViewListing extends JViewLegacy
{
// Overwriting JView display method
function display($tpl = null)
{
$model= & JModelLegacy::getInstance('Event','EventModel');
$pagination = $model->getPagination();
$this->assignRef('pagination', $pagination);
$JDoc =& JFactory::getDocument();
$db = JFactory::getDBO();
$sql = "SELECT * FROM #__event WHERE published = 1 ORDER BY id DESC";
$db->setQuery($sql);
$rows = $db->loadObjectList();
$sql2 = "SELECT * FROM #__user_usergroup_map WHERE group_id = 5 or group_id = 8";
$db->setQuery($sql2);
$rows2 = $db->loadObjectList();
$this->assignRef('rows',$rows);
$this->assignRef('rows2',$rows2);
// $JDoc->setTitle(' ');
// Display the view
parent::display($tpl);
}
}
in the default.php
<form action="<?php echo JRoute::_('index.php?option=com_event'); ?>" method="post" name="adminForm">
<?php echo $this->pagination->getListFooter(); ?>
<input type="submit" name="submit" value="GO!" />
</form>
hope someone could help
thank you!
The limits need to also be used in the queries to limit the number of records that are displayed to the page that you are on. Typically this can be done in the setQuery function, which allows a second and third parameter to set the limit size and start position.
$sql = "SELECT * FROM #__event WHERE published = 1 ORDER BY id DESC";
$db->setQuery($sql, $model->getState('limitstart'), $model->getState('limit'));
$rows = $db->loadObjectList();
// I'm not sure what this query is for, but since it probably isn't supposed to be limited to a set number of items, don't update it's setQuery call.
$sql2 = "SELECT * FROM #__user_usergroup_map WHERE group_id = 5 or group_id = 8";
$db->setQuery($sql2);
$rows2 = $db->loadObjectList();
I think that fixes the problem that you are having.
That being said, you have a host of minor issues that are making this a lot harder for you or just using outdated practices:
$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
Using JRequest::getVar() is deprecated and likely to be removed in future versions of Joomla. Instead use this:
$limitstart = JFactory::getApplication()->input->get('limitstart', 0, 'INT');
Note that the parameters have changed slightly. This uses a different class to parse input to the application.
$this->assignRef('rows',$rows);
The above is unnecessary anymore (was only needed back in PHP4 from what I understand). Instead just do $this->rows = $rows;
Finally, the big overall issue is that you aren't really using Joomla's help.
Your model should just be extending from the class JModelList since you are trying to create a list of events. If you extend from that class and name your functions properly, Joomla will do most of the work:
Rename _buildQuery to getListQuery.
Pretty much delete every other function in your model, since Joomla has all of them in JModelList doing basically the same things.
Update your view to this:
class EventViewListing extends JViewLegacy
{
// Overwriting JView display method
function display($tpl = null)
{
$JDoc = JFactory::getDocument();
$db = JFactory::getDBO();
$this->pagination = $this->get('Pagination');
$this->rows = $this->get('Items');
$sql2 = "SELECT * FROM #__user_usergroup_map WHERE group_id = 5 or group_id = 8";
$db->setQuery($sql2);
$this->rows2 = $db->loadObjectList();
// $JDoc->setTitle(' ');
// Display the view
parent::display($tpl);
}
}
$this->get() in the JViewLegacy class will call the model (with the same name as the view) and run the method of that model that starts with get followed by whatever word is in the function, so $this->get('Pagination') calls the models getPagination function.
And again, all of the functions that you are adding in the model exist already in libraries/legacy/model/list.php, so just use them!

Return multiple values from a method in a class

I am trying to return multiple variables from a method.
This is what I have tried so far:
This code is the method in the class:
public function getUserInfo(){
$stmt = $this->dbh->prepare("SELECT user_id FROM oopforum_users WHERE username = ?");
$stmt->bindParam(1, $this->post_data['username']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$user_id = $row['user_id'];
$thumb = $row['thumbnail'];
}
return array($user_id, $thumb);
}
I attempt to place each variable in a list for use in the calling program:
session_start();
require_once('init.php');
$username = trim($_POST['username']);
// create a new object
$login = new Auth($_POST, $dbh);
if($login->validateLogin()){
$_SESSION['loggedin'] = true;
list($user_id, $thumb) = $login->getUserInfo($user_id, $thumb);
echo $user_id . ' ' . $thumb;
}
This hasn't work.
How can I return an array of multiple variables from a method within a class for use in the calling program?
The method that you define in the class doesn't match what you are calling.
// In the class, you have:
getUserInfo();
// But you call this:
getUserInfo($user_id, $thumb);
Because of this, PHP thinks you are calling a different method, and thus returns nothing (at least nothing of use here).
Your call should look like this:
list($user_id, $thumb) = $login->getUserInfo(); //Note that there are no parameters.
Another Option
Something else you should look at is using an associative array. It would look something like this:
//In the class:
public function getUserInfo() {
...
return array(
'id' => $user_id,
'thumb' => $thumb
);
}
//And then for your call:
$user = $login->getUserInfo();
echo $user['id'].' '.$user['thumb'];
This would be my preference when coding something like this, as I prefer having an array for related things, as opposed to a set of independent variables. But that is all preference.
This is similar to this question- PHP: Is it possible to return multiple values from a function?
you can also take a look here. where they explain about ways to return multiple values - http://php.net/manual/en/functions.returning-values.php
One thing that I noticed is that in this line
list($user_id, $thumb) = $login->getUserInfo($user_id, $thumb);
You are passing 2 parameters here but in the function definition part you don't have parameters -
public function getUserInfo(){
.....
}
public function getUserInfo(){
$stmt = $this->dbh->prepare("SELECT user_id FROM oopforum_users WHERE username = ?");
$stmt->bindParam(1, $this->post_data['username']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$user_id = $row['user_id'];
$thumb = $row['thumbnail'];
$return[] = array($user_id, $thumb);
}
return $return;
}
You could create a class, e.g., UserInfo, specifically for holding user information and return that.
You could also return an associative array, e.g...
$userInfo = array(
'id' => ...,
'thumb' => ...
);
A third alternative is to use references, but in this context I recommend staying away from that.

Categories