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.
Related
I got the following array (the array is retrieved through a db query). Now, my question is, how do I get a single element like e_domains from the array mentioned below:
stdClass Object
(
[id] => 1
[uni_origin] => Aachen
[e_domains] => rwth-aachen.de
)
I got the output shown above by running the following line of codes:
if ($results ) {
foreach ( $results as $result ){
echo'<pre>'; print_r($result) ;
}
}
First off, that's not an array, that's an object. Like it says: "stdClass Object".
Access object properties like this:
$object->property_name
In your case, it would be:
$result->e_domains
There are much more to learn on the subject, like static properties, visibility etc. In your case, the above example will work.
Read more about classes and objects in the manual: http://php.net/manual/en/language.oop5.basic.php
Try this:
$e_domains = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
Hope it helpt.
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;
I have an array in yii2, and ocassionally it's only 1 single object that is not empty (all other element of array is empty) and I don't know which one is it. How can I either find the one that is not empty, or (my idea what I was trying), to create a new array, with array_filter (but I'm not sure if it works also with array of objects), to have only the one object in it.
if (count($ttepk) == 1) {
$ttep_filtered[] = array_filter($ttepk);
$id = $ttep_filtered[0]->id;
}
But it was also not working. I get the error message: PHP Notice – yii\base\ErrorException Trying to get property of non-object.
Before array_filter it looks like this:
Array
(
[3] => app\models\Model Object
(
after array_filter:
Array
(
[0] => Array
(
[3] => app\models\Model Object
(
So it seems, array_filter is not the one I need, or I use it the wrong way.
Can you please help me? Thank you!
You can try something like this
$filtered = array_filter($ttepk, function($item) {
return $item instanceof app\models\Model;
});
if (count($filtered) == 1) {
$id = reset($filtered)->id;
}
i am trying to call m custom function repeatedly with same or different parameters value,inside foreach loop parameters depending upon value to key provided my foreach.
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate=$this->getResult($username,$r->p_code);
print_r($toUpdate);
}
}
but when i am printing the latest query result i am getting $toUpdate get appended by latest parameter query.
Array
(
[query] => select * from `result` where (`studentid` = ?) and `studentid` = ? and `ccode` = ? and `a_no` = ? order by `date` desc limit 1
[bindings] => Array
(
[0] => XYZ
[1] => XYZ
[2] => course123code
[3] => 12321
)
[time] => 0.18
)
my user name getting same, while course code is get overrides while finding second result.
i want to get the result getResult() inside foreach loop so that it may give the related result for different parameters value.
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
This is a bad practice if you are fetching data from db inside the foreach loop.
BTW you can do this by keeping all new result in same array by index its some unique value, it will be look like this-
$toUpdate=array();
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate[$r->p_code]=$this->getResult($username,$r->p_code); // added $r->p_code as index to Array - $toUpdate
}
}
print_r($toUpdate); // this will give all the related result according your parameters
[UPDATE]
Try using unset($yourarray) for your next request these array will be new and they assign the new value each time -
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
unset($currentDetailOfUser);
unset($userdetail);
unset($condition_key);
unset($recentResult);
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
Hope this can help you.
I'm having an issue where I call the result_array() function on n query object from in codeigniter:
$this->db->select(array('a','b','c'));
$query = $this->db->get('basic');
print_r($query->list_fields());
$test = $query->result_array();
print_r($query->list_fields());
When I run this code, or:
$query = $this->db->get('basic');
print_r($query->list_fields());
print_r($query->list_fields());
or:
$query = $this->db->get('basic');
$test = $query->result_array();
print_r($query->list_fields());
The second list_fields() function always returns an array size 0, the first returns the correct list of field names.
In the last example where there is only one list_fields() function, the array is again size zero.
Any guidance in this matter will be greatly appreciated. I need the list_fields() function to be accessible after I read the result_array().
Here is the result of the first block of code:
Array
(
[0] => site_id
[1] => institution
[2] => caller
[3] => call_complete
[4] => call_details
[5] => id
[6] => timestamp
)
Array
(
)
Thank you, for your help
That looks to be a bug in the database driver. For example, in CI_DB_mysqli_result:
public function list_fields()
{
$field_names = array();
while ($field = $this->result_id->fetch_field())
{
$field_names[] = $field->name;
}
return $field_names;
}
A subsequent call will return array() because the while loop seeks over all the fields and leaves the pointer at the end of the list.
However, in the result class, result_id is public, so you can use mysqli_result::field_seek:
$query = $this->db->get('basic');
var_dump($query->list_fields());
// this should be called before any call to list_fields()
$query->result_id->field_seek(0);
var_dump($query->list_fields());
However, this is bad practise, as this only works for mysqli; for mysql, you'll need this:
mysql_field_seek($query->result_id, 0);
and for mssql:
mssql_field_seek($query->result_id, 0);
The correct way to do this is really to fix it in the database drivers. See this pull request :-)