Populate a variable in controller with single row data from a query - codeigniter

I have in a Codeigniter 4 controller this code:
$competicion =$db->table('competiciones')
->select('*')
->where('competiciones.slug', $blog_slug)
->get()->getRowArray();
How can I get and save in a variable id_competicion value, for example? I try this code but it is wrong:
$competicionid = $competicion->[competicion_id];

getRowArray() returns an array, the correct approach to retrieve an array value would be:
$competicionid = $competicion['competicion_id'];
another possibility would be to use getRow(), which returns an object. To retrieve an object value you could use:
$competicionid = $competicion->competicion_id;
read more: Generating Query Results: Result Rows

Related

Laravel Collection Filter breaking serialization format

I have a serialized String like this
$string = '[{"name":"FOO"},{"name":""},{"name":"BAR"}]';
I am trying to process it via Laravel Collection's filter method and eliminate items without a defined "name" property.
$collection = collect(\json_decode($string));
$collection = $collection->filter(function($v){
return !empty($v->name);
});
$string = \json_encode($collection->toArray());
dd($string);
Normally I am expecting something like this:
[{"name":"FOO"},{"name":"BAR"}]
But I'm getting something like this:
{"0":{"name":"FOO"},"2":{"name":"BAR"}}
Funny thing is, if I skip the filtering process or return true every time, I keep getting the string in the desired format. Removing the toArray() call has the same result. I don't want to keep the numeric indices as associative object keys.
Why this anomaly? And what should I do to get the serialized data in desired format?
In PHP arrays the index key must be unique.
In your case you have the key 'name' and collection automatically assigns the index key to all items in the collection.
To overcome that problem just call
$string = \json_encode($collection->values());

Eloquent Collections Where Condition

I want to get alternative products pictures.
dd($alternativeProduct->pictures);
When die and dump i get this result.
I need to get only the picture which is main. If main equals to 1. It is main picture.
When I write
dd($alternativeProduct->pictures->where('main', 1))
I got an empty array.
Here is my relation with Product and Picture relation
public function pictures(){
return $this->hasMany('App\Models\ProductPicture');
}
What can i do ?
The where method in a collection has three parameters: $key, $value and $strict, the last one defaults to true if not passed when calling the method. When $strict is true the comparison is done via === which does not do type coercion, meaning "1" === 1 is false.
From your dump data, I can see that "main" => "1" which means it's a string and you're passing an integer 1 to the where method, resulting in what I described above as a false condition and returning an empty result set. You can fix that by disabling strict comparison:
$alternativeProduct->pictures->where('main', 1, false);
// or the equivalent helper whereLoose
$alternativeProduct->pictures->whereLoose('main', 1);
Or passing a string as the value:
$alternativeProduct->pictures->where('main', "1");
That being said, if that's the only place you're using that collection in that request's context, I suggest that you filter the results at the database level, not after they are fetched, like so:
$alternativeProduct->pictures()->where('main', 1)->get();
Accessing the relations as a method ->pictures(), instead of as a property ->pictures, will return a Query Builder instance that allows you to add conditions to the database query and only fetch the actual items you need from the database, instead of fetching them all and filtering them out afterwards.
You may want to use whereLoose instead:
dd($alternativeProduct->pictures->whereLoose('main', 1))
From the Laravel docs:
The where method uses strict comparisons when checking item values. Use the whereLoose method to filter using "loose" comparisons.

Laravel Queries: 'lists' method

The 'lists' method surely does retrieve a list of column's values, but I want the method to retrieve the values but without duplication, how to achieve that?
$types = DB::table('events')->lists('type');
If you need to get just distinct values, you should do:
$types = DB::table('lists')->distinct()->lists('type');

Query result in codeigniter save in session display different results when used in controller functions using var_dump

I have used a CodeIgniter session to save result from database query in my model, for the first time I have used var_dump function to view the result save in the session variable and it's all okay but as I used thesame session to display the result to other function in my controller it only display the last row of the result not all the results that were originally save in the session.
**Students Controller**
function get_student(some parameters)
{
$print_result= $this->course_booking_model->get_student_ajax($config["per_page"],$page,$result,$tennant_id,$sort_by,$sort_order);
$this->session->set_userdata('print_result',$print_result);
$data['data_student'] = $this->session->userdata('print_result');
var_dump($this->session->userdata('print_result'));
}
Another function within thesame controller
function export_students()
{
$data['data_print']=$this->session->userdata('print_result');
$this->load->view('view_students_pdf',$data);
var_dump($this->session->userdata('print_result'));
}
The var_dump function will have different outputs
Try this approach:
Controller function 1:
$query = $this->course_booking_model->get_student_ajax($config["per_page"],$page,$result,$tennant_id,$sort_by,$sort_order);
$new_data=array(
'pdf_data' => $query
);
$this->session->set_userdata($new_data);
var_dump($this->session->userdata('pdf_data'));
Controller Function 2:
$data=$this->data;
$tennant_code=$this->session->userdata('username');
$query=$this->session->userdata('pdf_data');
var_dump($query);
When you use $this->session->set_userdata('print_result','value') you are setting the value of the variable just as if you were calling $print_result = 'value';, that means that the previous value will always be overwritten. If you wish to keep appending values to a session data variable I suggest you use an array as the value, you just will have to retrieve the current data and append a new element to the array each time you wish to update the value. Something like:
First value
$this->session->set_userdata('print_result',array($print_result));
Append new value
$this->session->set_userdata('print_result',array_push($this->session->userdata('print_result'),$new_result));

Code igniter with data mapper giving in valid json

I have this to select columns from a table and I want to pass this to Jquery ajax fn.
I am using below code but getting invalid json
My table has three column id, name and city but I am not selecting city
This is my json reponse
["{id:1,name\":\"JOHN\",\"city\":\"null\"}"
,"{\"id\":2,\"name\":\"MICHEAL\,\"city\":\"null\"}"]
Sadly the current stable (1.8.1) WanWizard datamapper DMZ_Json class double encode fields when you call all_to_json(). This issue seem to be fixed in the develop branch. You could workaround this multiple ways:
1. Call to_json() on individual model objects and create the json array with string manipulation:
$my_objects = (new Model)->get();
$results = array();
foreach ($my_objects as $o) {
$results[] = $o->to_json();
}
// building a json array from the strings returned by $o->to_json()
print '['.join(',', $results).']';
2. You can use the array extension's all_to_array method and json_encode that result:
$my_object_arrays = (new Model)->get()->all_to_array();
print json_encode($my_object_arrays);

Resources