Undefined offset: 0 with PHP array - php

I have the following code in my Symfony 2 web project in one of my repositories:
$result = $qb->getQuery()->getResult();
$converted = $this->transformArray($result);
return $converted[0];
My problem:
I get the following error which points to the last line:
Notice: Undefined offset: 0
Background:
My function transformArray() does the following:
private function transformArray($rows)
{
foreach ($rows as $i => $row) {
$rows[$i]['hexcolor'] = $this->convertColor($row['colorR'], $row['colorG'], $row['colorB']);
};
return $rows;
}
After this operation, my variable $converted contains an array like this with only one result:
array (
0 =>
array (
'subjectId' => 1234,
'subjectName' => 'English',
'hexcolor' => '#ff00'
)
)
Can anyone explain why doing $converted[0] (= trying to access the 0 index) results in an undefined offset error? Pasting the array output into a PHPFiddle and trying to access the 0 index works totally fine. How come it does not in my Symfony 2 project?

This is where going a little extra Mile with your code comes in handy. By that, it is meant something so simple as adding a few extra lines of code like so:
<?php
$result = $qb->getQuery()->getResult();
// DOES THE QUERY EVEN RETURN ANY RESULTS?
// IF NOT, SET $converted TO EMPTY ARRAY: WHY NOT?
$converted = (!empty($result)) ? $this->transformArray($result) : array();
// RETURN $converted[0] ONLY IF IT EXISTS, OTHERWISE NULL
return isset($converted[0]) ? $converted[0] : null;

Related

Laravel "undefined array key 0" that is actually defined

This is really weird. Laravel is telling me "undefined array key 0" but I am able to echo the value that Laravel can't seem to see and I can assign it to a variable.
$progress_check = db::select("select submitted, signed_off from users_to_stages where user_id = ? and sop_id = ? and stage_id = ?", [Auth::user()->id, $id, $do_stage_object->id]);
$thing = $progress_check[0]->submitted; // <-- $progress_check[0]->submitted contains 1
echo $thing;
exit;
And I get 1 returned from $thing. No errors. But! This:
$progress_check = db::select("select submitted, signed_off from users_to_stages where user_id = ? and sop_id = ? and stage_id = ?", [Auth::user()->id, $id, $do_stage_object->id]);
$thing = $progress_check[0]->submitted;
if($thing) {
$do_stages[$do_stage_object->id]['submitted'] = 1;
} else {
$do_stages[$do_stage_object->id]['submitted'] = 0;
}
Gives "Undefined array key 0" on the $thing = ... line that previously threw no error and successfully outputted the value (of 1).
If it helps, here's the print_r and dd of $progress_check:
print_r($progress_check);
Array
(
[0] => stdClass Object
(
[submitted] => 1
[signed_off] => 0
)
)
dd($progress_check);
array:1 [▼
0 => {#644 ▼
+"submitted": "1"
+"signed_off": "0"
}
]
I'm no expert on Laravel or object-oriented PHP (or object-oriented anything else for that matter) so maybe I'm just missing something I should know? Another pair of eyes was equally stumped though so... more eyes please!
I should mention, I'm running Laravel 8.83.22.
Edit: using db::table instead in line with ItsGageH's answer gives the same error and same situation with still being able to echo / assign it (as long as I don't then use if in an if) but slightly different contents in the DB results:
print_r($progress_check);
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[submitted] => 1
[signed_off] => 0
)
)
[escapeWhenCastingToString:protected] =>
)
Edit: bonus points (imaginary points though) if anyone can tell me what that 644 is?
You need to specify the table first, before the Select statement, then use where and get
So, you'd be looking at doing:
DB::table('users_to_stages')
->select('submitted, signed_off')
->where('user_id', '=', Auth::user()->id)
->where('sop_id', '=', $id)
->where('stage_id', '=', $do_stage_object->id)
->get();
Further Laravel select-statement reference here
The answer "Undefined array key 0" means you haven't define any first element with the 0 key. For instance: [0 => Auth::user()->id]
It seems you can workaround the problem without the [0] at $progress_check:
$progress_check = db::select("select submitted, signed_off from users_to_stages where user_id = ? and sop_id = ? and stage_id = ?", [Auth::user()->id, $id, $do_stage_object->id]);
$thing = $progress_check->submitted;
if($thing) {
$do_stages[$do_stage_object->id]['submitted'] = 1;
} else {
$do_stages[$do_stage_object->id]['submitted'] = 0;
}
Your bonus point:
644 is about the permission of reading or writing files, depending of what have been set up with chmod. This choice is often chosen, don't care about it.

Can't pass variable from controller to view in CodeIgniter

I am having a problem trying to pass a variable from the controller to the view. I think I am doing a mistake somewhere, I can't find it since I am new to it.
My controller Method is :
public function paymentdetail($order_code)
{
$this->load->model('Payment_Model');
$paymentDetail = $this->Payment_Model->getpaymentdetail($order_code);
$orderDetail = $this->Payment_Model->getOrderDetail($order_code);
// echo print_r($paymentDetail);
$datas['content'] = $this->load->view('payment/paymentDetail',
array('paymentDetail' => $paymentDetail,
'orderDetail' => $orderDetail), true);
$this->load->view('layouts/main_template', $datas);
}
The following model function getpaymentdetail() returns an array (result_array()) and this is the one I am concerned about. If I can work this one out then I can also work with other model methods.
$this->Payment_Model->getpaymentdetail($order_code);
When I type <?php echo $paymentDetail['column_name']; ?> in view file(PaymentDetail.php) I get an error
Undefined index: column_name
Why do I get this error?
model function getpaymentdetail() returns an array (result_array())
those arrays are normally structured like this:
Array
(
[0] => Array
(
[ID] => 3120
[column_name] => col1
)
)
hence you cannot access column_name via <?php echo $paymentDetail['column_name']; ?> as this index doesn't exist in your array structure.
if you move one index deeper, then it will work: <?php echo $paymentDetail[0]['column_name']; ?>
Attention, if you expect more than 1 row to be returned, above will only access the first result (indexed 0) row! You'd need a foreach loop to get all results, see Generating Query Results - result arrays

Codeigniter - passing multiple value to view

I am trying to build a month report with Codeigniter.
i have problem in parse value to view,
when i enable profiler, i get 12 month query
Controller
$this->load->model('dash_model');
$data1= $this->dash_model->get_user_all();
$ind = $this->dash_model->monthreport();
$this->output->enable_profiler(TRUE);
$data = array(
'mont' => $ind,
'blok' => $data1
);
print_r($data);
$this->parser->parse('blank', $data);
the output print_r data
Array
(
[mont] => Array
(
[0] => stdClass Object
(
[trans_email] => 0
)
)
and dash_model
for($i=1; $i<=12;)
{
$month=array("","01","2","3","4","5","6","7","8","9","10","11","12");
$m = $month[$i];
$query2=$this->db->query("select count(*) as trans_email from trans_email where lup LIKE '2014-$m%' ");
$i++;
}
return $query2->result();
how i get output select count(*) as trans_email from trans_email where lup LIKE '2014-01%' and next month to view ?
like
month 1 = 356 data
month 2 = 2000 data and next
i'm trying this : Codeigniter - passing multiple values to view
but nothing happens
update
i'm trying to add this code into dash_model
$i++;
$resultarray[$i]=$query2->result();
}
return $resultarray;
and i got some error
* Object of class stdClass could not be converted to string*
okay dude let me try to guest :D
let's assume you use array on your view, i can assume that because you initialize $data with array.
First make sure you read this userguide
on result_array() section.
then change $query->result(); to $query->result_array();
then try to var_dump() it, hope it's work
just pass it as
$data['mont'] = $ind;
$data['blok'] = $data1;
$this->parser->parse('blank', $data);
in the view get the data as of $ind as $mont
and $data1 as $blok.
You could do
$data = array();
$data['mont'] = $ind;
$data['blok'] = $data1;
Instead of declaring it then initializing it at the same time. (It also allow you to add/change data in it whenever you want in your controller).
Then do debug($data);to see if you got everything you want in $data.

post an array and iterate throught it in PHP codeigniter

This is the first time i create my own webservice (someone always did it for me before), so please bear with me.
I post this array :
$data = array(
'user_id' => $this->post('user_id'),
'group_id' => $this->post('group_id'),
'child_id' => $this->post('child_id'), //will be nested array
'custom' => $this->post('custom'),
'time' => $this->post('time'),
'date' => $this->post('date')
);
I tried to create a nested array with this : $this->post('child_id'), because user can post multiple child_id at once.
Then i tried to iterate through the child_id, because i need to insert them to the mysql :
for($i = 0; $i < sizeof($data['child_id']); $i++)
{
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data, $result_id[0]['id']);
}
What should i do, so i can have an array of child_id in my $data array? (nested array)
And how to iterate through it?
UPDATE :
I have updated the codes above.
I use advanced rest client for testing, and i tried to post something like this in the form content type :
child_id=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id=2
Notice that theres two child_id (left most and right most), but only the last one (right most) is inserted.
And this is the add_trans in the model :
function add_trans($table, $data, $schedule_id) {
$query = $this->db->insert($table, array('child_id' => $data['child_id'], 'schedule_id' => $schedule_id));
return $query;
}
Thanks a lot for your time.
Even thought you set the name attribute as child[] on the markup,
You still need to call it as:
'child_id' => $this->post('child_id')
It will still return an array.
for($i = 0; $i < sizeof($data['child_id']); $i++) {
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data, $result_id[0]['id']);
}
EDIT:
Looking upon you query string, that seems to be the culprit:
child_id=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id=2
^ same index , same index, same index, it will overwrite and you will get only `2`
If you want to get them all into an array format, you need to set them like this
child_id[]=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id[]=2
^ it needs to be set like this
UPDATE:
And in your model, if you want each id per row, well you can also loop in this case:
function add_trans($table, $data, $schedule_id) {
foreach($data['child_id'] as $child_id) {
$query = $this->db->insert($table, array('child_id' => $child_id, 'schedule_id' => $schedule_id));
}
// return $this->db->insert_id();
return $query;
}
ofcourse that won't work, it has to be
for($i = 0; $i < sizeof($data['child_id']); $i++)
{
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data['child_id'][$i], $result_id[0]['id']);
}
because you've not set $data['child_id[]'] so it doesn't exist, the key is just a string or number, it does not validate or parse anything
you don't need to give child[] in post method. just give only child, it will get complete array what are you sending from views
replace
'child_id' => $this->post('child_id[]')
with
'child_id' => $this->post('child_id')

DB query in for loop errors on second loop (PHP, Codeigniter)

A simple loop loops through an array and deletes database records...
Controller:
foreach ($deletedTags as $deletedTag) {
$tagId = $this->tags_model->get_tag_id($deletedTag);
$this->tags_model->delete_tag_association_by_tag($workId, $tagId);
}
$deletedTags is an array, an example being:
Array ( [0] => purple [1] => trees [2] => green )
Model:
function get_tag_id($tag) {
$this->db->where('tags.name', $tag);
$query = $this->db->get(self::TABLE);
return $query->row()->id;
}
When there is only one value in $deletedTags it works fine. When there's more than one value the model function get_tag_id($tag) breaks on the second loop. It errors on the line return $query->row()->id; with:
Undefined property: stdClass::$id
Any idea why?
I've solved it. For some reason it's erroring because it can only find the first tag in the array in the db (even though the other tags do exist in the db). I added a tag_exists check and all is fine...
foreach ($deletedTags as $deletedTag) {
if ($this->tags_model->tag_exists($deletedTag)) {
$tagId = $this->tags_model->get_tag_id($deletedTag);
$this->tags_model->delete_tag_association_by_tag($workId, $tagId);
}
}
Weird.

Categories