Echoing the data from data array passed to view in code igniter - php

So I'm trying to echo specific values from the array, but I get message:
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/drilldown.php
Line Number: 92
that many times.
Heres the result of print_r of the array:
Array ( [0] => Array ( [productCode] => S10_1949 [productName] => 1952 Alpine Renault 1300 [productLine] => Classic Cars [productScale] => 1:10 [productVendor] => Classic Metal Creations [productDescription] => Turnable front wheels; steering function; detailed interior; detailed engine; opening hood; opening trunk; opening doors; and detailed chassis. [quantityInStock] => 7305 [buyPrice] => 98.58 [MSRP] => 214.3 [image] => S10_1949.jpg ) )
View Code:
$follow = $p['0'];
foreach($follow as $item) {
echo $item->productCode;
}
Model Code:
public function getProduct($p)
{
$this->db->where('productCode', $p);
$resultset = $this->db->get('products');
return $resultset->result_array();
}
Controller Code:
function drillDown()
{
$productID=$this->uri->segment(3);
$data['p']=$this->littlemodel->getProduct($productID);
$this->load->view('drillDown',$data);
}
Can anybody please help?

I believe you just want one row from the database.
You should be using
return $resultset->row()
So in the model, try this:
public function getProduct($p)
{
$this->db->where('productCode', $p);
return $this->db->get('products')->row();
}
Keep the controller code the same.
In the view, use this:
echo $p->productCode;
This is just an optimized way of fetching your requirements. In case of any trouble, do let me know. Will be happy to help.

Related

Trying to get property of non-object error on object

I'm getting the following error reports:
Severity: Notice
Message:
Trying to get property of non-object
Using gettype() I can see that it's a proper object.
A print_r() returns:
stdClass Object ( [campaigngroupid] => 3 [name] => And another one [dt_created] => 2014-02-04 17:11:21 [created_userid] => 1 [deleted] => 0 )
Echoing out $object->name for example works fine, but still, I'm getting this notice...
The object is set using CodeIgniter's ->row() from a database query result.
All I can ask is, sup?
Try this in your model, Suppose $query holds the query object:
function some_model_function(){
..........
..........
if($query->num_rows() > 0 ){
return $query->row();
}
return FALSE;
}
Also check whether the notice is from any where else.

Use returned data from array

I get some data from a table
Data is returned into an array like this
Array ( [id_widget] => 11 [id_user] => 7 [active] => 1 )
Then I am trying to use this "id_widget" and "entryemail" to insert them into another table.
"newentry" comes from an input, but I don't know how to post the "id_widget"
This is my model function
public function addentry($data) {
$this->db->insert('entries', array(
'id_widget' => $data['id_widget'],
'entryemail' => $data['entryemail']
));
}
This is my controller function:
public function entercontest() {
$entry = array(
'id_widget' => $this->widget[0]['id_widget'],
'entryemail' => $_POST['entryemail']
);
$this->model->addentry($entry);
}
It works to insert "entryemail" if I comment id_widget line everywhere.
The error doesn't occur when getting the value from the array $data['id_widget']. The error occurs in the entercontent function because you're populating the array with an undefined value because $this->widget is undefined.
Make sure $this->widget is defined and has the data before using it.

CodeIgniter: view is not generated in a certain case

Starting from a variable called $data, which is an associative array which includes an object, and whose printed value is this:
Array
(
[item] => stdClass Object
(
[id] => 1
[tipo] => 0
[idioma] => es
[nombre] => Artí­culo de prueba
[titulo] => Esto es un artí­culo de prueba
[alias] => articulo-de-prueba
[texto] => Lorem ipsum etc etc
[url] =>
[video] =>
[fecha_c] => 2012-11-27 10:50:37
[fecha_m] => 2012-11-27 17:00:00
[fecha_p] => 2012-11-28 00:00:00
[destacado] => 0
[status] => 1
)
[imagenes] => Array
(
)
)
I need to filter its value and assign it to another array, this way:
protected function load_form($data = '') {
$this->load->helper('form');
// If item data have been sent, pass it to the form view to edit it.
// Else display empty form for new item.
if (! empty($data)) {
// Data can be an associative array with an object and another array or just an object
if (array_key_exists('item', $data)) {
$this->_vars['item'] =& $data['item'];
}
else {
$this->_vars['item'] =& $data;
}
if (array_key_exists('imagenes', $data)) {
$this->_vars['imagenes'] = $data['imagenes'];
}
}
$view = $this->load->view(ADMIN_FORMS_PATH . $this->_controller . '_form', $this->_vars, true);
/*DEBUG*/ echo $view; // just for debugging purposes
}
The first assignment generates these errors:
A PHP Error was encountered Severity: Notice Message: Undefined index:
item Filename: core/Admin_Controller.php Line Number: 205
A PHP Error was encountered Severity: Notice Message: Object of class
stdClass could not be converted to int Filename:
core/Admin_Controller.php Line Number: 205
It behaves like the item index doesn't exist, and it does. Also, it tries to convert the object to an integer.
Why does it happen and what should I do to fix it?
EDIT:
I was doing &= instead of =&. That's the reason of the errors.
Anyway, the problem persists and the code seems to stop.
EDIT2:
Trying to redefine the problem. It might be something related to CodeIgniter, so I've added the whole function, including CodeIgniter functions.
The load_form() method can be invoked from a request to create a new item, in which case $data is empty, or from a request to edit a given item (in $data). In the first case (creation), the debug line is executed, but not in the second case (edition).
This may be your issue. Near the end you have"$datos['imagenes'];" where it should be "$data['imagenes'];"
if (! empty($data)) {
// Data can be an object, or an array with object + array of images
if (array_key_exists('item', $data)) {
$this->_vars['item'] &= $data['item'];
}
else {
$this->_vars['item'] = $data;
}
if (array_key_exists('imagenes', $data)) {
$this->_vars['imagenes'] = $data['imagenes'];
}
}
Problem solved. It was too simple.
It was inside the view. I was trying to echo:
$item['id']
instead of
$item->id
The item data is being retrieved as an object, not an array. It was causing the problem silently, without any warning, notice or error.
Anyway I appreciate your quick help.

How do I declare 'sub-objects' in PHP

I'm relatively new to OOP in PHP, and I'm not sure if what I'm trying to do is possible or recommended. In any case, I can't figure it out. I'd appreciate any pointers to tutorials or documents which might help - I'm not expecting a full-blown answer here.
I have a system in which each user has a number of 'Libraries'. Each Library contains a number of 'Elements'.
DB set up is as follows:
user_libraries
- id (unique)
- user_id (identifies user)
- name (just a string)
elements
- id (unique)
- content (a string)
library_elements
- id (unique)
- library_id
- element_id
where library_id is the id from user_libraries, and element_id is that from elements.
I want to be able to access a given user's library, and their elements.
I've set up the library class, and can use it to retrieve the list of libraries (or a sub-list).
I do this like this:
$mylibraryset = new LibrarySet();
$mylibraryset->getMyLibraries();
which gives (when I use print_r):
LibrarySetObject (
[user_id] => 105
[data_array] => Array (
[0] => Array (
[id] => 1
[user_id] => 105
[type] => 1
[name] => My Text Library
)
[1] => Array (
[id] => 2
[user_id] => 105
[type] => 2
[name] => Quotes
)
)
)
Now, what I'd like to be able to do is for each of those libraries (the elements in data_array), to retrieve all the elements.
The best idea I've had so far is to do something like:
foreach($mylibrary->data_array as $library) {
$sublibrary = new Library();
$sublibrary -> getAllElements();
}
where Sublibrary is another class which has the function getAllElements. I can't quite get it to work though, and I'm not sure I'm on the right lines...
Is there a way that I can then end up being able to do something like this:
$mylibrary->sublibraries[0]->element[0]
to retrieve a specific element?
As I say, I don't expect a full-blown explanation here - just pointers to get me started.
<?php
class Library {
public $element;
public $data;
public function __construct($sublibrary) {
$this->data = $sublibrary;
}
public function getAllElements() {
// populate $this->element using $this->data
}
}
class LibrarySet {
public $user_id;
public $data_array;
public $sublibraries;
public function getMyLibraries() {
// populate $this->data_array
$this->sublibraries = Array();
foreach($this->data_array as $index => $sublibrary) {
$this->sublibraries[$index] = new Library($sublibrary);
$this->sublibraries[$index]->getAllElements();
}
}
}
$mylibraryset = new LibrarySet();
$mylibraryset->getMyLibraries();
$mylibraryset->sublibraries[0]->element[0]
?>

Get a PHPActiveRecord result as simple array, not array of objects

I would like to have a simple a method, that can give back PHP Activerecord results as simple/associative arrays, not an array of ActiveRecord Objects.
In Ruby I believe this is done perhaps with .map() method. (I am not a Ruby guy...)
What I want is a simple method call, like toArray() in Zend_DB_Table, not a foreach, or something like that, but I can't seem to find it in their docs.
In PHP ActiveRecord getting a result is really easy:
$settings = SystemSettings::all();
But it gives back something like this:
[0] => SystemSettings Object
(
[errors] =>
[attributes:ActiveRecord\Model:private] => Array
(
[param] => author
[value] => Hawle
)
[__dirty:ActiveRecord\Model:private] => Array
(
)
[__readonly:ActiveRecord\Model:private] =>
[__relationships:ActiveRecord\Model:private] => Array
(
)
[__new_record:ActiveRecord\Model:private] =>
)
[1] => SystemSettings Object
(
[errors] =>
[attributes:ActiveRecord\Model:private] => Array
(
[param] => base_url
[value] => example.com
)
[__dirty:ActiveRecord\Model:private] => Array
(
)
[__readonly:ActiveRecord\Model:private] =>
[__relationships:ActiveRecord\Model:private] => Array
(
)
[__new_record:ActiveRecord\Model:private] =>
)
While this is really great in many cases, here, I would just like to have a simple array, like this:
Array
(
[author] => Hawle
[base_url] => example.com
)
I had a similar issue hopefully this can help someone else who stumbles on it. Obviously, this is specific to phpactiverecord.org.
In /lib/Model.php I added the following function:
public function to_array(array $options=array())
{
return $this->serialize('array', $options);
}
In /lib/Serialization.php I added the following class
class arraySerializer extends Serialization
{
public static $include_root = false;
public function to_s()
{
return self::$include_root ? array(strtolower(get_class($this->model)) => $this->to_a()) : $this->to_a();
}
}
I can then call ->to_array() and get an array back.
Hope this helps!
I was searching for the answer to this question in order to produce an array of results that could be easily json-encoded and sent as the response to an ajax call. I wanted only the attributes of each object in the array of results.
Unfortunately, you can't just call to_json() on each result and then json-encode the entire thing; you end up with double-encoding. Fortunately, though, the function and class posted by #willwashburn to solve this problem have now been included in php-activerecord, though they don't seem to have made it into the online documentation.
To return an array of results, do the following:
$data = MyModel::find('all');
foreach ($data as &$result) {
$result = $result->to_array();
}
Your entire result set will now be an array of arrays, containing only the attributes of each object. You can then do something like
echo(json_encode($data));
if you want to send it as the response to an ajax call.
This is my solution:
$posts = Post::find('all');
$arrayResult = array_map(function($res){
return $res->attributes();
}, $posts);
printf('<pre>%s</pre>', print_r($arrayResult, true));
class MyPHPActiveRecord extends PHPActiveRecord {
public function toJSON() {
return json_encode(get_object_vars($this));
}
}
You could do it like this:
funciton ar2array($settings){
$arr = array();
foreach($settings as $fieldObj){
$fieldName = $fieldObj->attributes["param"];
$fieldValue = $fieldObj->attributes["value"];
$arr[$fieldName] = $fieldValue;
}
return $arr;
}
$resultAsYouWant = ar2array($settings);
Hope this helps. Cheers
PS: If ->attributes is private use its accesor method (there must be one) as ->getAttributes() or equivalent.
I found this looking for solution of the same problem that I encountered using Yii framework - there is simplier way to do this in Yii.
$posts = Posts::model()->findAll();
foreach($posts as $result)
{
print_r($result->attributes);
}
It prints simple array as requested:
Array
(
[id] => 1
[title] => Title
[text] => Text
)
Hope it helps somebody.
My solution:
Added the following method to the utils class found in lib\Utils.php
public static function results_to_json($data)
{
$arr = array();
if(count($data)>0){
foreach($data as $row){
array_push($arr, $row->to_array());
}
}
return json_encode($arr);
}
Call by:
echo \ActiveRecord\Utils::results_to_json($dataobject);
Obviously this is no longer relevant to the OP; however, considering that it still took me over an hour to find a solution for this (no thanks to php-activerecords docs), this may help someone else.
$r = Model::find('$id')->attributes();
$a = [];
foreach ($r as $k => $v)
{
$a[$k] = $v;
}
Perhaps not the most elegant, but works perfectly.

Categories