Notice: Undefined Offset php - php

I have this php code which throws the alert notice: undefined offset
$thisMonth=$_POST['month']; //the value is today's date's month
$thisYear=$_POST['year']; //the value is today's date's year
$thisDay=$_POST['day']; //the value is today's date's day
$table=mysql_query("SELECT * FROM `kids` WHERE `debt`!='0'") or die(mysql_error());
$debt=0;
while($row=mysql_fetch_assoc($table)){
$explodedDate=explode('/',$row['enrollmentdate']);
$theYear=$explodedDate[0];
$theMonth=$explodedDate[1]; //this line throws the error
$theDay=$explodedDate[2]; //and also this line
if((int)$theYear==(int)$thisYear && (int)$theMonth==(int)$thisMonth){
if((int)$theDay==(int)$thisDay || (int)$thisDay==0){
$debt+=$row['debt'];
}
}
}
I have been reading all over the internet for a solution but seems like this error is dependent on the code and unfortunately I can't seem to figure out how to fix it.
any ideas how to fix the error or what's causing it?
this is the full error:
Notice: Undefined offset: 1 in C:\wamp\www\kids_house\php\functions.php on line 600
Notice: Undefined offset: 2 in C:\wamp\www\kids_house\php\functions.php on line 601

The reason that these two lines are throwing errors is because the value in this is not yyyy/mm/dd, as you expect:
$explodedDate=explode('/',$row['enrollmentdate']);
If you look at the value that throws the error with something like this, you should see the issue:
$thisMonth=$_POST['month']; //the value is today's date's month
$thisYear=$_POST['year']; //the value is today's date's year
$thisDay=$_POST['day']; //the value is today's date's day
$table=mysql_query("SELECT * FROM `kids` WHERE `debt`!='0'") or die(mysql_error());
$debt=0;
while($row=mysql_fetch_assoc($table)){
$explodedDate=explode('/',$row['enrollmentdate']);
if ( count( $explodedDate ) <= 1 ) {
var_dump( $row ); //this will show you the row that is causing the notice
var_dump( $explodedDate ); //this will show you the date
die();
}
$theYear=$explodedDate[0];
$theMonth=$explodedDate[1]; //this line throws the error
$theDay=$explodedDate[2]; //and also this line
if((int)$theYear==(int)$thisYear && (int)$theMonth==(int)$thisMonth){
if((int)$theDay==(int)$thisDay || (int)$thisDay==0){
$debt+=$row['debt'];
}
}
}
If you want to retry with commas for lines with an enrollment date formatted like yyyy,mm,dd you could do this. It's not the most elegant solution, but it sounds like you have dirty data so may have to.
$thisMonth=$_POST['month']; //the value is today's date's month
$thisYear=$_POST['year']; //the value is today's date's year
$thisDay=$_POST['day']; //the value is today's date's day
$table=mysql_query("SELECT * FROM `kids` WHERE `debt`!='0'") or die(mysql_error());
$debt=0;
while($row=mysql_fetch_assoc($table)){
$explodedDate=explode('/',$row['enrollmentdate']);
//try again with commas
if ( count( $explodedDate ) == 0 ) {
$explodedDate=explode(',',$row['enrollmentdate']);
}
//skip the record if still no enrollment date
if ( count( $explodedDate ) == 3 ) {
$theYear=$explodedDate[0];
$theMonth=$explodedDate[1]; //this line throws the error
$theDay=$explodedDate[2]; //and also this line
if((int)$theYear==(int)$thisYear && (int)$theMonth==(int)$thisMonth){
if((int)$theDay==(int)$thisDay || (int)$thisDay==0){
$debt+=$row['debt'];
}
}
}
}

Related

How to use the result of mysql query as the column name of another query

i have a following code
<?php
include("includes\conn.php");
$start = $_POST['start_date'];
$end = $_POST['end_date'];
$result = mysqli_query($con,"SELECT * FROM data");
while($row = mysqli_fetch_assoc($result)){
$time_stamp = $row['time_stamp'];
$temp_date= substr($time_stamp, 2, 12);
$date= explode('.', $temp_date);
$final= $date[2]. '-' .$date[1]. '-' .$date[0];
$result1 = mysqli_query($con,"SELECT * FROM data WHERE $final BETWEEN $start AND $end");
while($row2 = mysqli_fetch_assoc($result1)){
print_r($row2);
}
}
?>
Error:
Notice: Undefined offset: 2 in C:\xampp\htdocs\Nestle\trend_test.php on line 10
Notice: Undefined offset: 1 in C:\xampp\htdocs\Nestle\trend_test.php on line 10
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, bool given in C:\xampp\htdocs\Nestle\trend_test.php on line 12
Your kind help is needed!
Your date extraction from time_stamp might be a problem.
$final= substr($time_stamp, 0, 10)
would be better.
If needed include Quotation marks at start and end of date items within query.
Add another echo for $final before calling MySQL and you can understand better and correct yourself.
Lets assume that this is the data of the date in your db '09.12.2019 12:54:50' so in order to get the format yyyy-mm-dd, hence your date format has date and time, first is you remove the time:
$temp_date= substr('09.12.2019 12:54:50', 0, 10);
After getting the date, we will be making it to this format yyyy-mm-dd
$date= explode('.', $temp_date);
$final= $date[2]. '-' .$date[1]. '-' .$date[0];
As a result, $final has a value 2019-12-09 [yyyy-mm-dd] and you can now use it in the next query.
Since your date values in db uses '.' (09.12.2019 12:54:50) instead of
'-' (09-12-2019 12:54:50), we made an approachable solution in it.

Fixing "Warning: Illegal string offset" -- (but without losing content)

I have searched for solution for this problem but none fix my problem.
The answers suggest that I use isset to check the array before working on it. But I will explain how it doesnt do it for me later.
Pre-req:
I've got a huge XML file from a tour & travel webservice which I would parse and convert to PHP array and later do some operation on it. (Filter tours mostly).
My Approach:
I'm using SimpleXML to load the xml and convert it to PHP array like so:
$xml = file_get_contents(APPPATH."tour.xml", true);
$xmlString = htmlentity_to_xml($xml); //custom method to clean XML
$Str = simplexml_load_string($xmlString, 'SimpleXMLElement', LIBXML_NOCDATA);
//converting to array
$json = json_encode($Str);
$array = json_decode($json,TRUE);
Then I'm sending this array to a fitlerTours($searchParams, $tourArray) method along with search parameters (cityName & dates) and the array itself.
Then using foreach() i'm going through each tour to look for the cityName and raising a flag if found.
The Problem
When I filter the tours (the ones which contain cityName) for dates, I'm getting this.
Severity: Warning
Message: Illegal string offset 'year'
Filename: controllers/tourFilter.php
Line Number: 78
Warning shows for offeset 'month' and 'day' also.
Here's my PHP for date filter: (Line 78 is 4th line)
if($flag == 1){
if(!empty($fromDate)){
foreach($tour['departureDates']['date'] AS $date){
$dateDep = strtotime($date['year'] . "-" . (($date['month']) < 10 ? "0".$date['month'] : $date['month']) . "-" . (($date['day']) < 10 ? "0".$date['day'] : $date['day']));
if(strtotime($fromDate) <= $dateDep && $dateDep <= strtotime($fromDate . "+".$range." days")){
if($date['departureStatus'] != "SoldOut"){
$dateFlag = 1;
}
}
}
}
else{
$dateFlag = 1;
}
$flag = 0;
}
if($dateFlag == 1){//Collect tours which contain the keyword & dates to $response array
$responseArray[] = $tour;
$dateFlag = false; //Reset Flag
}
Here's the snippet of XML:
...
<departureDates>
<date>
<day>7</day>
<month>1</month>
<year>2016</year>
<singlesPrice>12761</singlesPrice>
<doublesPrice>9990</doublesPrice>
<triplesPrice>0</triplesPrice>
<quadsPrice>0</quadsPrice>
<shipName/>
<departureStatus>Available</departureStatus>
</date>
<date>
<day>8</day>
<month>1</month>
<year>2016</year>
<singlesPrice>12761</singlesPrice>
<doublesPrice>9990</doublesPrice>
<triplesPrice>0</triplesPrice>
<quadsPrice>0</quadsPrice>
<shipName/>
<departureStatus>SoldOut</departureStatus>
</date>
</departureDates>
...
Now if i use the solution I found by searching around is check if the array is set properly by isset() it doesn't return true and line 78 is not executed and the data is lost. But I need the data.
This happens for only keywords i search.
Any help is appreciated.
The error says that the $date var is detected as string in some point...
Characters within strings may be accessed and modified by specifying
the zero-based offset of the desired character after the string using
square array brackets, as in $str[42]. Think of a string as an array
of characters for this purpose.
See here
So try this:
if(is_array($date)){
$dateDep = strtotime($date['year'] . "-" . (($date['month']) < 10 ? "0".$date['month'] : $date['month']) . "-" . (($date['day']) < 10 ? "0".$date['day'] : $date['day']));
if(strtotime($fromDate) <= $dateDep && $dateDep <= strtotime($fromDate . "+".$range." days")){
if($date['departureStatus'] != "SoldOut"){
$dateFlag = 1;
}
}
}
else {
//If this is not an array what is it then?
var_dump($date);
}

Read text from a file and load a new string from a row every 24 hour

After some hours of research I made this script:
function get_string_on_interval($strings, $interval) {
return $strings[round((time()/$interval - floor(time()/$interval)) * sizeof($strings))];
}
echo get_string_on_interval(file('matlista.txt'), 60*60*24);
In this matlista.txt I have a specific word on each row/line.
This script shows a string from this text file on my site but the problem is that it doesn't start showing from index 1 (which is row/line 1) it starts from the line 46.
I don't know what I'm doing wrong but I want this script to read from line 1 and after 24 hours it should go to line 2 and so on and display the different lines every 24 hour. This script starts to show line 46 and continues from there, I can't find the problem.
$data = array(
'line1',
'line2',
'line3'
);
function get_string_on_interval($strings, $interval)
{
$startTime = '2014-03-11 18:14:00';
return $strings[floor((time() - strtotime($startTime)) / $interval)
% count($strings)];
}
echo get_string_on_interval($data, 10);
And $startTime is the datetime from which you want to 'count' the lines (when the first line is shown). Example should change the line every 10 seconds.

Undefined offset: 1 using mysql_real_escape_string($data[0])

Good day again guys. APOSTROPHES gettin on my nerve. Please Help guys! I get this error when the RESPO column have an APOSTRPHE word on it "OFFICE'S".
Notice: Undefined offset: 1 in xxx:\xxxx\www\ptoms2\reports\view_reports.php on line 14
Notice: Undefined offset: 1 in xxx:\xxxx\www\ptoms2\reports\view_reports.php on line 15
My line 14 and 15 are this codes which this makes the error lines:
$month = date("m", strtotime($data[1]));
$year = date("Y", strtotime($data[1]));
To sum up all my view_reports.php are this following:
<?php
$respo = $_GET['respo'];
$data = explode("+", ($respo));
$month = date("m", strtotime($data[1]));
$year = date("Y", strtotime($data[1]));
$viewrecord = "SELECT dv.*, dv.respo, (pr.pr_gsis_c + pr.pr_gsis_l) AS deduction FROM tbl_dv dv LEFT OUTER JOIN tbl_payroll pr on dv.dv_id = pr.dv_id LEFT OUTER JOIN tbl_payroll tpr on tpr.dv_id = dv.dv_id WHERE dv.respo='".mysql_real_escape_string($data[0])."' && year(dv.date_added)=$year && month(dv.date_added)=$month ";
$run_viewrecord = mysql_query($viewrecord) or die(mysql_error());
{
etc....
THank you in advance. I gettin this error for a week and so.. I never imagine that just this APOSTROPHES making this error.. Please Help!
EDIT: This is the actual code I have.. I tried to inject mysql_real_escape_string maybe this is the solution of most APOSTROPHES error. But nothin is working..
This is a DROPDOWN Generated report. In the report.php I choose a RESPO and will gather all RESPO respectively upon the month I selected too.. BUT I have a RESPO that is PROV'L BUDGET OFFICE. WHich the PROV'L contains a APOSTROPHE.. WHEN I Generate the report according to this RESPON I got that error.. and the address is like this:
http://xxxxx/xxxxxx/reports/view_reports.php?respo=PROV
it should be like this sample without apostrophe:
http://xxxxx/xxxxx/reports/view_reports.php?respo=BIPC%2B2014-02-04+10%3A53%3A04
You need to use urlencode / decode on the $_GET value passed so it will not truncate the information after the apostrophe. That will resolve your problem.
You would use decode on the code posted above like so:
$respo = urldecode($_GET['respo']);
The code you are preparing this statement from would be:
$variable = urlencode($row['somethinghere']
Now if it contains an apostrophe it would still send the entire string of data just fine.

Outputting the name of the month instead of the number

I have a query which returns 3 fields, one of which is the month as a two digit number.
I want to basically have it so if month == 1 output january, if month == 02 output febuary etc
This is what I am trying, but this does not work at all, and prevent the entire column from being displayed in PHP.
while ($row = mysql_fetch_array($sqlstr)) {
if ($row['theMonth']=="6") {
echo "<td>{June}</td>";}
echo "<td>{$row['sumSales']}</td>";
echo "<td>{$row['sumPurchases']}</td>";
echo "</tr>";
}
}
What is the correct way to do what I want, and why is what I am doing wrong?
The SQL query I am using is:
SELECT theMonth, sum(Sales) as sumSales, sum(Purchases) as sumPurchases
FROM
( SELECT date_format(saledate, '%Y-%m') AS theMonth, sales.cost as Sales, 0 AS Purchases
FROM sales, products
WHERE sales.product=products.name AND category='Food' OR category='Bocas'
OR category='Bebidas' OR category='Flor de cana por botellas'
OR category='Vino por botella' OR category='hora feliz'
UNION ALL
SELECT date_format(purchasedate, '%Y-%m') AS theMonth, 0 as Sales, purchases.cost as Purchases
FROM purchases
) AS all_costs
group by theMonth
I donĀ“t think I could just replace
SELECT date_format(purchasedate, '%Y-%m') AS theMonth
with
SELECT MONTHNAME(purchasedate) AS theMonth
So what would be the best way to return the month name as text in SQL?
In your SQL you can use DATE_FORMAT to convert a date to a month name:
SELECT DATE_FORMAT(NOW(), '%M')
July
The list of allowable specifiers can be found in the MySQL documentation.
(MONTHNAME should also work too.)
The reason why your current method doesn't work is because you are currently outputting both the year and the month (e.g. "2010-06") and this string doesn't compare equal to the string "6".
.
function month_name($int) {
return date( 'F' , mktime(1, 1, 1, (int)$int, 1) );
}
echo month_name(2); // February
First option would be to modify your SQL query to return the month as a name rather than (or as well as) a numeric. See MONTHNAME
Second option would be to use PHP's date functions to generate the name for you
$monthName = date('F',mktime(1,1,1,$row['theMonth'],1,2010));
Third would be to use a monthnames array, similar to zebediah's suggestion
There is probably a php builtin for that, but not using anything like that
$monthNames = array(1 => "January", 2 => "Febuary", 3 => "March", .... 12 => "December");
while ($row = mysql_fetch_array($sqlstr)) {
echo "<td>{$monthNames[$row['theMonth']]}</td>";
echo "<td>{$row['sumSales']}</td>";
echo "<td>{$row['sumPurchases']}</td>";
echo "</tr>";
}
You've got a closing curly brace at the end of the line on your first echo statement. That's causing PHP to prematurely terminate the conditional block, then it has a parse error when it stumbles across your last closing curly brace since it doesn't have an opening match.
You can get the name of the month from a timestamp (if you have one) with the date function. date('F', $timestamp); see the php date function reference
Doing it in the SQL statement is probably your easiest and most performance-friendly way of handling this particular situation.

Categories