Codeigniter retrieve data immediately on controller - php

How can I retrieve a data from my database in the controller, and assign it to a variable, that I will send to the view?
$data['schedule'] = $this->SectionsModel->getschedule($section);
I want the
$schedule['teacher']
(as equivalent to a view) data from the statement above to be passed to a variable, but how?
I tried this one but it shows an error
$data['schedule'] = $this->SectionsModel->getschedule($section);
foreach ($data['schedule'] as $key => $value){
echo $value['teacher'];
}

may be you can use result_array() in return value of your model.

Check your getschedule() method in your SectionModel if it's using the function result() instead of result_array().
The difference between the two methods is that result() will return object while result_array() will return array.
In you case,
$data['schedule'] = $this->SectionsModel->getschedule($section);
foreach ($data['schedule'] as $key => $value){
echo $value['teacher'];
}
Maybe $data['schedule'] is an object.You must use,
$data['schedule'] = $this->SectionsModel->getschedule($section);
foreach ($data['schedule'] as $key => $value){
echo $value->teacher;
}
If you will use result_array() method in your getschedule() in SectionModel to return result, do like this,
$data['schedule'] = $this->SectionsModel->getschedule($section);
foreach ($data['schedule'] as $key => $value){
echo $value['teacher'];
}
Hope this will help.

Related

Laravel Foreach Controller vs View

I realized something I can't figure out by myself.
I get a different result when I loop through first in a Controller and pass then the result to my view. Versus loop straight in my view.
For instance:
I have this in my Controller:
public function index()
{
$subscribers = Subscriber::where('user_id', Auth::user()->id)->orderBy('created_at','asc')->get();
foreach ($subscribers as $key => $subscriber) {
$var = $subscriber->name;
}
return view('backend.newsletter.contacts.index')->withSubscribers($subscribers)
->withVar($var);
}
by using {{$var}} in my view I get only "John" as a result.
But when I use the foreach loop in my view instead of in the Controller:
#foreach($subscribers as $key => $subscriber)
{{$subscriber->name}}
#endforeach
I get two results, "John" and "Dan". This makes totaly sense as I have two entries in my DB.
So how does it come that I get two different results here ?
When you're doing this:
foreach ($subscribers as $key => $subscriber) {
$var = $subscriber->name;
}
With each iteration you overwrite $var so you always get the last value. For example, if you have ['Dan', 'John, 'Alice', 'Alan'], you'll get Alan.
Good practice is too pass data to a view and iterate it with #foreach.
Because only the last loop iteration is stored in $var.
You need to
$var = [];
foreach ($subscribers as $key => $subscriber) {
$var[] = $subscriber->name;
}
You are overriding $var in the loop.
Try this:
$var = [];
foreach ($subscribers as $key => $subscriber) {
$var[] = $subscriber->name; // Appends name to array
}

Foreach array within an object

I've got a PHP object. One of the values within the object is in array. I'm trying to get a foreach to just read the array within the object but it doesn't seem to be working.
PHP:
foreach ($object->ArrayName as $value) {
echo $value;
}
is there any way of doing this?
well, if you have an object but you don't know which property is an array, you need to catch them all and verify if they are an array:
// get each value of the object and call it as property
foreach(get_object_vars($object) as $property) {
// if this property is an array...
if (is_array($property) {
// ... access to every value of that array
foreach($property as $value) {
// $property is your array and $value is every value
// here you can execute what you need
}
}
}
Use
is_array($obj)
to validate whether it's an array or not.
you said your php object contains arrays, hence you need to use 2 foreach loops like this.
<?php
foreach($object->ArrayName as $value) {
foreach($value as $item) {
echo $item;
}
}
?>
if the loop is withing the object wich mean inside the class use $this instead :
foreach ($this->ArrayName as $value) {
echo $value;
}

Replacing an item in an object?

I'm looping through an object:
foreach ($data as $asset) {
$asset->test = 'test';
}
test exists in $data and is set to something else, I wish to replace it with 'test'.
The above fails to work. Where am I going wrong?
You should use referenced loop with & like foreach ($data as &$asset)
foreach ($data as &$asset)
{
$asset->test = 'test';
}
Referenced loop will have an effect to $data, otherwise only current $asset object changes.
You can think about using a function that already exists, like array_walk that would execute your function.
function test_exists(&$asset) {
$asset->test = "test";
}
array_walk($data, "test_exists");

Update object value within foreach loop

I would like to loop through the contents of a query object update certain values and return the object.
function clearAllIds($queryObject)
{
foreach($queryObject->result() as $row)
{
$row->id = 0;
}
return $queryObject
}
In this example I would like to zero out all of the ID values. How can I accomplish this within the foreach loop?
Please excuse the formatting.
This entirely depends on what the class of your query object is, and whether or not you'll be able to Pass by reference.
Assuming your $queryObject->result() can be delivered in a write-context, you could preface the $row with an ampersand to pass it by reference, like so:
foreach($queryObject->result() as &$row)
{
$row->id = 0;
}
function clearAllIds($queryObject)
{
foreach($queryObject->result() as &$row)
{
$row->id = 0;
}
return $queryObject
}
Use the & operator to get $row as a reference.
Edit: This will work if $queryObject is an array. You should probably do
$data = $queryObject->result();
foreach($data as &$row) { ... }
return $data;
function trim_spaces($object)
{
foreach (get_object_vars($object) as $property=> $value)
{
$object->$property=trim($value);
}
}
//no need to return object as they are passed by reference by default

decode mysql query before returning it to view

I'm running a query to mysql that returns encrypted data. I'd like, if possible, to decode the results before sending it to the view. It seems like better form to handle the decoding in the controller (or even the model) rather than inside the view.
I can't seem to wrap my head around how to do it, though.
I was thinking I could iterate through the object, decodode it, and push it to another array that would be sent to the view. Problem with this is I won't know (and need to keep) the indexes of the query.
So the query might return something like:
[id] => 742
[client_id] => 000105
[last] => dNXcw6mQPaGQ4rXfgIGJMq1pZ1dYAim0
[first] => dDF7VoO37qdtYoYKfp1ena5mjBXXU0K3dDlcq1ssSvCgpOx75y0A==
[middle] =>iXy6OWa48kCamViDZFv++K6okIkalC0am3OMPcBwK8sA==
[phone] => eRY3zBhAw2H8tKE
Any ideas?
Ended up with:
function name(){
$data['e_key']=$this->e_key;
$clid = $this->uri->segment(3);
$name = $this->Clients_model->getNameData('*','client_id='.$clid,'');
$nameArray= array();
foreach ($name->result() as $row){
$x = $row;
$keys = array('id','client_id');
$unenc = array();
foreach ($x as $key=>$value){
if(! in_array($key, $keys)){
$unenc[$key]=$this->encrypt->decode($value,$this->e_key);
}else{
$unenc[$key]=$value;
}
}
array_push($nameArray,$unenc);
}
$data['name'] = $nameArray;
$this->load->view('names/name_view',$data);
}
Assuming you know how to decrypt the data, it's but a matter of iterating over the object, decrypting the encrypted fields.
If $YOUR_OBJECT is your object and your function for decryption is decode() then the following code should do the trick.
// The keys corresponding to the encrypted fields
$encoded = array('last', 'first', 'middle', 'phone');
$decoded = array();
foreach($YOUR_OBJECT as $key => $value)
{
if (in_array($key, $encoded))
{
$decoded[$key] = decode($value);
}
}
if it's a particular index, you could decode it like
$result['last'] = base64_decode($result['last']);
or in the model, use mutators and accessors:
public function setUp() {
$this->setTableName('tablename');
$this->actAs('Timestampable');
$this->hasMutator('last', '_encode64');
$this->hasAccessor('last', '_decode64');
}
protected function _encode($value) {
$this->_set('last',base64_encode($value));
}
protected function _decode($value) {
return base64_decode($value); // not sure on this one - might have to
// return $this->set('last', base64_decode($value));
}

Categories