PHP Undefined Offset Within Class - php

This one's been bugging me for the past day now. Here's the code:
public function getUserCredits()
{
$dbl = new databaseManager();
$dbl->connect_simp();
$ret = $dbl->queryDB("SELECT * FROM users WHERE `USER_ID` = ".$this->userId);
$this->userCredits = $ret['USER_CREDITS'];
return $this->userCredits;
}
Now when I try to run this code, I get an undefined offset error. Nothing too strange about it when I first saw it, but now it's happening more and more and I can't figure out why.
I can use var_dump(); and var_export(); and it displays the contents of the returned array absolutely fine.
EDIT:
array(1) {
[0]=>
array(50) {
["USER_ID"]=>
string(10) "0000000001"
[0]=>
string(10) "0000000001"
["USER_USERNAME"]=>
string(8) "SampleUsername"
[1]=>
string(8) "SampleUsername"
["USER_PASSWORD"]=>
string(32) "5f4dcc3b5aa765d61d8327deb882cf99"
[2]=>
string(32) "5f4dcc3b5aa765d61d8327deb882cf99"
["USER_EMAIL"]=>
string(0) ""
[3]=>
string(0) ""
["USER_LEGION"]=>
string(1) "1"
[4]=>
string(1) "1"
["USER_ENERGY"]=>
string(4) "2812"
[5]=>
string(4) "2812"
["USER_MAX_ENERGY"]=>
string(4) "2812"
[6]=>
string(4) "2812"
["USER_SHIELD"]=>
string(2) "20"
[7]=>
string(2) "20"
["USER_MAX_SHIELD"]=>
string(2) "20"
[8]=>
string(2) "20"
["USER_HULL"]=>
string(2) "60"
[9]=>
string(2) "60"
["USER_MAX_HULL"]=>
string(2) "60"
[10]=>
string(2) "60"
["USER_CREDITS"]=>
string(19) "9223372036854775807"

try
$ret[0]['USER_CREDITS']
instead of
$ret['USER_CREDITS']

You gotta fetch a row first (I assume you extend mysqli).
$result = $dbl->queryDB("SELECT * FROM users WHERE `USER_ID` = ".$this->userId);
$row = $dbl->fetch_assoc($result) ;
$this->userCredits = $row['USER_CREDITS'];

At first you should watch the result record. As you are getting the details in an array of your database record fetched and it is in array format with numeric keys. Use what #AbuOmar said.

AS your var_dump($ret), Try this to assign user credit otherwise if it is not set, assign 0 value.
if(isset($ret[0]['USER_CREDITS'])){
$this->userCredits = $ret[0]['USER_CREDITS'];
}
else{
$this->userCredits = 0;
}

Related

Select cookie value based on string match

So I have this if statement where I am looking for a cookie:
if (isset($_COOKIE['OptanonConsent'])) {
...
}
Next, I'm breaking the cookie up using the explode function:
$cookie_array = explode("&", $_COOKIE['OptanonConsent']);
Which gives me the following output:
array(9) {
[0]=> string(26) "landingPath=NotLandingPage"
[1]=> string(67) "datestamp=Tue+Apr+12+2022+07:16:23+GMT-0500+(Central+Daylight+Time)"
[2]=> string(14) "version=6.33.0"
[3]=> string(30) "groups=C0001:1,C0002:0,C0004:0"
[4]=> string(6) "hosts="
[5]=> string(14) "isGpcEnabled=0"
[6]=> string(13) "geolocation=;"
[7]=> string(17) "isIABGlobal=false"
[8]=> string(23) "AwaitingReconsent=false"
}
Next, I want to filter through and just grab the array index that has "groups" in it, using the following:
$groups_array = array_filter($cookie_array, static function($value) {
return str_contains($value, 'groups');
});
Which outputs:
array(1) {
[3]=> string(30) "groups=C0001:1,C0002:0,C0004:0"
}
Next, I want to search and see if "C0004:0" exists, so I'm using:
$targeting_cookie_disabled = in_array('C0004:0', $groups_array, true);
But that is returning a false return. The index changes always, so I can't use $groups_array[3].
Does anyone know how to properly break up the cookie and grab just the "groups" index of an array and search through it?

How to sort a $_POST array by date string

I have a POST array passed on submission of a form. I loop through it and put the results into a table using this:
<table id="myTable">
<thead>
<tr><td>Exam Date</td><td>Subject Name</td><td>Subject Code</td><td>AM/PM</td></tr>
</thead>
<tbody>
<?php
$rowCount = count($_POST['exam_code_input']);
//var_dump($_POST);
for($i=0; $i<$rowCount; $i++)
{
echo "<tr>";
echo "<td>".$_POST['exam_date_input'][$i]."</td>";
echo "<td>".$_POST['exam_code_input'][$i]."</td>";
echo "<td>".$_POST['exam_title'][$i]."</td>";
echo "<td>".$_POST['exam_time_input'][$i]."</td>";
echo "</tr>";
}
?>
</tbody>
</table>
I need to sort the table rows by the date. At the moment it puts the entries into the table by index. This is the var_dump($_POST)
array(13) {
["your_name"]=> string(8) "Ian TEST"
["candidate_number"]=> string(5) "12345"
["centre_number"]=> string(4) "TEST"
["school_year"]=> string(2) "12"
["email"]=> string(23) "ianbutler82#yahoo.co.uk"
["mobile_number"]=> string(11) "12345455676"
["exam_board"]=> string(2) "-1"
["exam_date_input"]=> array(7) {
[0]=> string(10) "05/16/2017"
[1]=> string(10) "05/08/2017"
[2]=> string(10) "05/12/2017"
[3]=> string(10) "05/25/2017"
[4]=> string(10) "06/06/2017"
[5]=> string(10) "06/12/2017"
[6]=> string(10) "06/20/2017"
}
["exam_code_input"]=> array(7) {
[0]=> string(9) "Arabic AL"
[1]=> string(10) "Biology AL"
[2]=> string(10) "Biology AL"
[3]=> string(10) "Biology AL"
[4]=> string(10) "Biology AL"
[5]=> string(10) "Biology AL"
[6]=> string(10) "Biology AL"
}
["exam_title"]=> array(7) {
[0]=> string(34) "Understanding and Written Response"
[1]=> string(14) "Biology Unit 3"
[2]=> string(14) "Biology Unit 6"
[3]=> string(14) "Biology Unit 1"
[4]=> string(14) "Biology Unit 2"
[5]=> string(14) "Biology Unit 4"
[6]=> string(14) "Biology Unit 5"
}
["exam_time_input"]=> array(7) {
[0]=> string(2) "AM"
[1]=> string(2) "PM"
[2]=> string(2) "PM"
[3]=> string(2) "PM"
[4]=> string(2) "PM"
[5]=> string(2) "PM"
[6]=> string(2) "AM"
}
["token"]=> string(32) "bd62bdf4ba8a00174281499decb94d87"
["btSubmit"]=> string(18) "Generate Timetable"
}
So you want to sort the "exam_date_input"-Array, right? And it does correspond with the other data, like in "exam_code_input"?
With DateTime::createFromFormat you can create first an DateTime object from your date values (eg 05/08/2017) and then get the Timestamp out of it (getTimestamp()).
Then I would suggest you iterate through your POST-Data like you're already doing and create a new array for better data structure.
Like
array( "{THETIMESTAMP}" => {all the other corresponding data, like in exam_code_input} )
With ksort() you can sort the array by the keys ascending.
You need to use your own sorting function.
function array_sort_by_column(&$array, $column, $direction = SORT_ASC) {
$reference_array = array();
foreach($array as $key => $row) {
$reference_array[$key] = $row[$column];
}
array_multisort($reference_array, $direction, $array);
}
And call is like:
array_sort_by_column($events_array, 'date');
var_dump($events_array);
You can use usort for this
usort($myArray, function($a,$b){
return ((new DateTime($a['DatesColumn'])) < (new DateTime($b['DatesColumn']))) ? -1 : 1;
});

how to find the last message from conversation using group by

I was expecting it was easy but stuck to the problem to find the list of the conversation using group by sender receiver array, Here above is snapshot of the database
I have followed the above sequence using group by sender id and receiver id but stuck in getting the conversation which is unique
here is the query
SELECT tbl_registration.name as sender_name,group_concat(message SEPARATOR '|') as message_list,`sender_reciever_array`,`datetime`,`reciever_id`,`sender_id` FROM `tbl_chatting_view`
inner join
tbl_registration
on tbl_registration.id=tbl_chatting_view.sender_id
group by `sender_reciever_array`
which produces the following results in php array
array(5) {
[0]=>
array(6) {
["sender_name"]=>
string(7) "harshit"
["message_list"]=>
string(4) "k|my"
["sender_reciever_array"]=>
string(4) "2,29"
["datetime"]=>
string(19) "2016-08-06 13:34:09"
["reciever_id"]=>
string(2) "29"
["sender_id"]=>
string(1) "2"
}
[1]=>
array(6) {
["sender_name"]=>
string(7) "harshit"
["message_list"]=>
string(5) "mohan"
["sender_reciever_array"]=>
string(3) "2,5"
["datetime"]=>
string(19) "2016-08-08 12:18:45"
["reciever_id"]=>
string(1) "5"
["sender_id"]=>
string(1) "2"
}
[2]=>
array(6) {
["sender_name"]=>
string(5) "admin"
["message_list"]=>
string(9) "jkgh|test"
["sender_reciever_array"]=>
string(4) "29,5"
["datetime"]=>
string(19) "2016-08-02 11:31:45"
["reciever_id"]=>
string(1) "5"
["sender_id"]=>
string(2) "29"
}
[3]=>
array(6) {
["sender_name"]=>
string(5) "admin"
["message_list"]=>
string(56) "Jhadjksdhjkahsjkhdfjshfjhdsjfh|Asdasfdfs|Hgasdhjgdhgsahj"
["sender_reciever_array"]=>
string(5) "29,63"
["datetime"]=>
string(19) "2016-08-12 12:47:53"
["reciever_id"]=>
string(2) "63"
["sender_id"]=>
string(2) "29"
}
[4]=>
array(6) {
["sender_name"]=>
string(10) "Kiran sahu"
["message_list"]=>
string(156) "Asdafdggfhgfj|HhjjhhjjhhFghxfzcgc
Bnasbdjnbfjdjfh
Ninja admonishments
Njkdnsfjkndgnkdfn
|Ghjgsdfhjgfh|Sadas|Dgfjdjkjkhsjkjkas
Dsjmjkdsljflkjsdlkfcjklsd"
["sender_reciever_array"]=>
string(5) "63,29"
["datetime"]=>
string(19) "2016-08-13 05:39:56"
["reciever_id"]=>
string(2) "29"
["sender_id"]=>
string(2) "63"
}
}
Here in the above array there is the last message will come in the message array with the list with the seperator as '|', and in the sender and reciever array there contains in the two array 63,29 and 29,63 but I need the combination of the two message
You could mess around with this. Normalize your GROUP BY to contain both sides of the conversation? I'm no SQL expert, so downvote away. (receiver is spelled wrong) :D
SELECT IF(tcv.sender_id > tcv.reciever_id,
concat_ws(',', tcv.reciever_id, tcv.sender_id),
concat_ws(',', tcv.sender_id, .tcvreciever_id)
) as both
FROM tbl_chatting_view tcv
GROUP BY both

Getting value with key from multidimensional array not returning expected result

I'm currently trying to loop over an array and only get specific values with key 1, but for some reason it's giving me another array instead of the string value I'm trying to retrieve.
//using firstElement variable to skip first row of excel sheet
$firstElement = true;
foreach ($arrayData as $excelData){
if($firstElement){
$firstElement = false;
}
else{
$latinName = array_column($excelData, 1);
var_dump($latinName);
if(strtolower($latinName) == strtolower($target3[0])){
echo('target is already in database' . PHP_EOL);
}
else{
echo($latinName . 'should be written to database' . PHP_EOL);
}
}
}
this is the current for each loop I'm using. The variable arrayData is an array with every result I'm getting from an excel sheet. My goal is to get the specific field latinName from each row.
result from the variable dump is a list of arrays:
[121]=>
array(7) {
[0]=>
string(14) "Knolboterbloem"
[1]=>
string(19) "Ranunculus bulbosus"
[2]=>
string(7) "Plantae"
[3]=>
string(13) "Magnoliophyta"
[4]=>
string(12) "Angiospermae"
[5]=>
string(14) "Basal eudicots"
[6]=>
string(12) "Ranunculales"
}
My goal is to get every value with key 1 from those arrays and assign them to variable latinName using this code (edited this code to test Mark Bakers answer):
$latinName = array_column($excelData, 1);
But whenever I print out the value from latinName I get another array instead of the String value:
array(17) {
[0]=>
NULL
[1]=>
string(10) "Poa annua "
[2]=>
string(22) "Alopecurus myosuroides"
[3]=>
string(22) "Echinochloa crus-galli"
[4]=>
string(17) "Apera spica-venti"
[5]=>
string(14) "Milium vernale"
[6]=>
string(14) "Lolium perenne"
[7]=>
string(20) "Agrostis stolonifera"
[8]=>
string(15) "Holcus lanatus "
[9]=>
string(14) "Avena sterilis"
[10]=>
string(19) "Digitaria ischaemum"
[11]=>
string(15) "Setaria viridis"
[12]=>
string(20) "Setaria verticillata"
[13]=>
string(18) "Cyperus esculentus"
[14]=>
string(16) "Eragrostis minor"
[15]=>
string(13) "Holcus mollis"
[16]=>
string(17) "Scirpus maritimus"
}
I don't use PHP that often, but why is my variable latinName getting turned into an array?
Any help would be greatly appreciated and sorry for the messy post.

PHP Associative Arrays with Variable Key Names

I am trying to create an associative array with the keys being email addresses and the values being passwords. It is reading from an XML database to get the information. Here is my code:
$data = simplexml_load_file("Treasury.xml");
//Add in all passwords
for ($i = 0; $i < count($data->Member); $i++) {
$key = $data->Member[$i]->Email + '';
$USERS[$key] = $data->Member[$i]->Pin;
}
The problem comes in the for loop. It gets a correct count of the members (I had that print out) but the key is always being labeled as the number 0, resulting in only the last pin being stored in an array on length 1. Is there something syntactically that I am doing wrong?
Thanks in advance.
EDIT: I did a var_dump of the first user in the XML document. Here it is (Sorry for how long it is):
object(SimpleXMLElement)#4 (5) { ["Name"]=> string(19) "Mackenzie Daugherty" ["PC"]=> object(SimpleXMLElement)#2 (0) { } ["Email"]=> string(16) "dau53688#obu.edu" ["Pin"]=> string(4) "0000" ["Payments"]=> object(SimpleXMLElement)#3 (1) { ["Payment"]=> array(2) { [0]=> object(SimpleXMLElement)#5 (7) { ["Type"]=> string(4) "Dues" ["Description"]=> string(18) "Dues for Fall 2013" ["DateIssued"]=> string(7) "8/26/13" ["DateEnd"]=> string(6) "9/9/13" ["Owed"]=> string(2) "55" ["Paid"]=> string(2) "55" ["Plan"]=> object(SimpleXMLElement)#7 (5) { ["InPlan"]=> string(1) "0" ["PlanDescription"]=> object(SimpleXMLElement)#8 (0) { } ["Intervals"]=> string(1) "0" ["Completed"]=> string(1) "0" ["PerInterval"]=> string(1) "0" } } [1]=> object(SimpleXMLElement)#6 (7) { ["Type"]=> string(19) "Tiger Tunes Tickets" ["Description"]=> string(18) "Two Saturday Night" ["DateIssued"]=> string(7) "8/26/13" ["DateEnd"]=> string(7) "8/26/13" ["Owed"]=> string(2) "30" ["Paid"]=> string(2) "30" ["Plan"]=> object(SimpleXMLElement)#7 (5) { ["InPlan"]=> string(1) "0" ["PlanDescription"]=> object(SimpleXMLElement)#8 (0) { } ["Intervals"]=> string(1) "0" ["Completed"]=> string(1) "0" ["PerInterval"]=> string(1) "0" } } } } }
As clearly stated in the documentation that I'm sure you've been studying carefully, the PHP concatenation operator is ., not +.
Your code takes two operands, and attempts to perform arithmetic addition on them. Since they are not [meaningful] numbers, you end up with 0.
(I couldn't give a more detailed assessment without knowing the precise values of your operands, which you did not provide.)
Your code should read:
$key = $data->Member[$i]->Email . '';
// ^
// (is the concatenation necessary at all?
// isn't Email already a string?)
Make the same correction elsewhere.

Categories