Show SINGLE RECORD with newest expiration date - php

I am using a FFDB database (flat File Database).
This script works as long as $vinc field has the same value, but I have 5 different types of $vinc values R1, R2, R3, R4, R5 - if I add new record where $vinc is not R1, a blank page appears instead.
<?php
function getbyfunction($selectfn, $orderby = NULL, $includeindex = false)
{
if (!$this->isopen)
{
user_error("Database not open.", E_USER_ERROR);
return false;
}
// If there are no records, return
if ($this->records == 0)
return array();
if (!$this->lock_read())
return false;
// Read the index
$index = $this->read_index();
// Read each record and add it to an array
$rcount = 0;
foreach($index as $offset)
{
// Read the record
list($record, $rsize) = $this->read_record($this->data_fp, $offset);
// Add it to the result if the $selectfn OK's it
if ($selectfn($record) == true)
{
// Add the index field if required
if ($includeindex)
$record[FFDB_IFIELD] = $rcount;
$result[] = $record;
}
++$rcount;
}
$this->unlock();
// Re-order as required
if ($orderby !== NULL)
return $this->order_by($result, $orderby);
else
return $result;
}
function returnRec($item){
if($item)
return true;
}
$db = new FFDB();
if (!$db->open("foo"))
{
$schema = array(
array("key", FFDB_INT, "key"),
array("status", FFDB_STRING),
array("vinc", FFDB_STRING),
array("month", FFDB_STRING),
array("day", FFDB_INT),
array("year", FFDB_INT)
);
// Try and create it...
if (!$db->create("foo", $schema))
{
echo "Error creating database\n";
return;
}
}
$result = $db->getbyfunction("returnRec", "vinc");
show_rec(end($result));
function show_rec($record){
$number = $record["key"];
$Rvinc = $record["vinc"];
$Rstatus = $record["status"];
$Rday = $record["day"];
$Rmonth = $record["month"];
$Ryear = $record["year"];
$tday = getdate();
$current_year = $tday['year'];
$current_month = $tday['month'];
if (($status == ON) && ($vinc == R1) && ($month >= $current_month) && ($year == current_year)){
echo "myrecord $vinc $status $day $month $year";
}
?>
Any help?!
Thanks
Yegge, using show_rec($result[0]); it shows 1 record but instead the most recent expiration date is showing the latest expiration date:
i.e.:
1 record expire 08/01/2011
2 record expire 11/01/2011
show_rec($result[0]); is showing the record with expiration date 11/01/2011 instead of 08/01/2011
Yegge
show_rec(end($result)); worked as long as $vinc == R1 only, if adding another record where vinc is not R1 then shows a blank page, any ideas?

<?php
function getbyfunction($selectfn, $orderby = NULL, $includeindex = false)
{
if (!$this->isopen)
{
user_error("Database not open.", E_USER_ERROR);
return false;
}
// If there are no records, return
if ($this->records == 0)
return array();
if (!$this->lock_read())
return false;
// Read the index
$index = $this->read_index();
// Read each record and add it to an array
$rcount = 0;
foreach($index as $offset)
{
// Read the record
list($record, $rsize) = $this->read_record($this->data_fp, $offset);
// Add it to the result if the $selectfn OK's it
if ($selectfn($record) == true)
{
// Add the index field if required
if ($includeindex)
$record[FFDB_IFIELD] = $rcount;
$result[] = $record;
}
++$rcount;
}
$this->unlock();
// Re-order as required
if ($orderby !== NULL)
return $this->order_by($result, $orderby);
else
return $result;
}
function returnRec($item){
if($item)
return true;
}
$db = new FFDB();
if (!$db->open("foo"))
{
$schema = array(
array("key", FFDB_INT, "key"),
array("status", FFDB_STRING),
array("vinc", FFDB_STRING),
array("month", FFDB_STRING),
array("day", FFDB_INT),
array("year", FFDB_INT)
);
// Try and create it...
if (!$db->create("foo", $schema))
{
echo "Error creating database\n";
return;
}
}
$result = $db->getbyfunction("returnRec", "vinc");
foreach($result as $item) {show_rec($item);break;}
function show_rec($record){
$number = $record["key"];
$Rvinc = $record["vinc"];
$Rstatus = $record["status"];
$Rday = $record["day"];
$Rmonth = $record["month"];
$Ryear = $record["year"];
$tday = getdate();
$current_year = $tday['year'];
$current_month = $tday['month'];
if (($status == ON) && ($vinc == R1) && ($month >= $current_month) && ($year == current_year)){
echo "myrecord $vinc $status $day $month $year";
}
?>
i think you need to use break in loop, like above.

select product, expirationdate from your_table
where expirationdate > {current_date} order by expirationdate ASC limit 1
{current_date} is variable that should be passed from php or you can use mysql function instead

If I understood your code correctly, instead of
foreach($result as $item) {show_rec($item);break;}
//use
show_rec($result[0]); //only show the very first item in the result array
Edit: Then use this:
show_rec(end($result));

SOLUTION:
I just want to make sure to post the solution:
$result = $db->getall(lp_month,lp_year);
$i = 0;
foreach ($result as $row){
print_r (show_record($row));
if ($i >= 1)
break;
$i++;
}
Not a lot different from what I initially had, but print_r instead of echo did the trick:
print_r (show_record($row));
Thanks

Related

Detecting a cycle in an array PHP

I'm running a simple script which puts an integer through the formula of the Collatz conjecture and adds the output of each step into an array.
I want to use a function to detect if there's a cycle in the array, using Floyd's algorithm. And though I feel like I'm not doing a bad job, I don't seem to get it right. At this moment I'm getting the error Trying to get property 'next' of non-object in C:\xampp\htdocs\educom\week3\functions.php on line 12
See my code below. Any feedback is greatly appreciated!
include("functions.php");
$n = $_POST['number'];
$step = 0;
$reeks1 = array();
$cycle = 0;
echo "Your entry is: ". $n ."<br><br>";
while($n!==1 && $cycle==0){
$cycle = detect_cycle(array($reeks1));
if($n % 2 == 0){
$n = $n / 2;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}else{
$n = ($n * 3) + 1;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}
}
functions.php:
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node->next;
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit->next == NULL){
return FALSE;
}else{
$turtle = $turtle->next;
$rabbit = $rabbit->next->next;
}
}
return FALSE;
}
Check this out. IMPORTANT I don't know is this according to your theory. but it won't give you errors if you use like this.
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node[0];
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit[0] == NULL){
return FALSE;
}else{
$turtle = $turtle[0]; // use the number of the element key starting from 0
$rabbit = $rabbit[0][1];
}
}
return FALSE;
}

Trying to get property of non-object PHP Laravel

I know that this question in the tittle is asked WAYY too much in here, and I went thru most of them but still cant find a solution for my code.
function calculatingWages($project_id){
$start_date = '2017-05-01';
$end_date = '2017-12-31';
$project = Project::find($project_id);
$users = $project->users()->get();
$sumWage=0;
foreach ($users as $user){
$timesheetHours = $user->timesheets()->whereBetween('timesheets.date',[$start_date,$end_date])->sum('hours');
$wages = UserWage::whereBetween('start_date',[ $start_date,$end_date])->whereBetween('end_date',[ $start_date,$end_date])->get();
foreach ($wages as $wage){
$value = $wage->value;
$currency = $wage->currency;
$sumWage = extractMonthsAndCalculate($value,$currency, $timesheetHours, $start_date, $end_date);
}
return $sumWage;
}
}
function extractMonthsAndCalculate($value,$currency, $timesheetHours, $start_date, $end_date){
$start = Carbon::createFromFormat('Y-m-d',$start_date)->month;
$end = Carbon::createFromFormat('Y-m-d',$end_date)->month;
$diffOfMonths = $end - $start;
$sumWage = 0;
for ($i = $start; $i <= $diffOfMonths; $i++) {
$wageYear = Carbon::createFromFormat('Y-m-d',$start_date)->year;
$wageDay = Carbon::createFromDate($wageYear,$i,'01')->lastOfMonth()->toDateString();
$test = convertingALL($value,$currency,$timesheetHours,$wageDay);
}
return $sumWage;
}
function convertingALL($value, $currency, $timesheetHours, $date)
{
$currencyObj = Exchange::where('date',$date)->get()->first();
$currencyDate = $currencyObj->date;
$hourlyWage = 0;
$sumWage = 0;
if($currencyDate == $date) {
$dollar = $currencyObj->dollar_lek;
$euro = $currencyObj->euro_lek;
if ($currency == 'ALL') {
$sumWage = $value;
} elseif ($currency == 'USD') {
$sumWage = ($hourlyWage *$timesheetHours) * $dollar;
} else {
$sumWage = ($hourlyWage *$timesheetHours)* $euro;
}
}else{
$euro = 140;
$dollar = 136.4;
if ($currency == 'ALL') {
$sumWage = $value;
} elseif ($currency == 'USD') {
$sumWage = $value * $dollar;
} else {
$sumWage = $value * $euro;
}
}
return $sumWage;
}
it says that it cant get the property of a non object in line 468
this is line 467-468:
$currencyObj = Exchange::where('date',$date)->get()->first();
$currencyDate = $currencyObj->date;
when I dd $currencyDate it prints the date of it, tried to parse it using carbon but still same thing, where am I messing up?
You need to tell Eloquent that the date field contains a date (even though it seems obvious).
Docs: https://laravel.com/docs/5.4/eloquent-mutators#date-mutators
In your Exchange model you should have
class Exchange extends Model {
protected $dates = [ 'date' ];
On an unrelated note, ->get()->first() will pull every single result back from the database, then chuck all but one of them away. If you just call ->first() then you'll only get one result from the database; same end result but better for performance.

How to use regular expression in the WHERE clause of query in Laravel?

I have a table named "Shows". There is a column "show_date". I want to retrieve the shows whose show_date is todays date.
Following is my query
$s = DB::table('shows')->get();
$a = DB::table('shows')->select('show_date')->get();
foreach ($s as $key => $value)
{
$date_test = date('Y-m-d');
$s_test = DB::table('shows')->where('show_date',preg_grep('/"'.$value->show_date.'"./', $a->show_date))->get();
echo "<pre>"; var_dump($s_test);
if(explode(" ",$value->show_date)[0] == date('Y-m-d'))
{
$shows1 = DB::table('shows')->where('id',$value->id)->get();
$s1 = DB::table('transactions')
->select(DB::raw("GROUP_CONCAT(selected_seats SEPARATOR '') as selected_seats"),'userid','amount','show_id')
->where("show_id","=",$value->id)
->groupBy('userid')
->groupBy('amount')
->orderBy('userid','ASC')
->orderBy('amount', 'DESC')
->get();
if($s1 != null)
{
echo $value->id;
$c = count($s1);
$sub_count1 = 0; $next_id = ""; $total_array = 0;
for($i=0;$i<$c;$i++)
{
$first_character = $s1[$i]->selected_seats;
$sub_count = substr_count($s1[$i]->selected_seats, ',');
$sub_count1 = $sub_count1 + $sub_count;//to get the total no. of seats
for($j=0,$k=0;$j<$sub_count;$j++,$k++)
{
// split the string with comma.
$s = explode(',',$first_character);
// get total no. of seat names listed in one row in table.eg A 1,B 2. Then $sub_count would be 2
$p = $s[$j][0];
}
}
// get seats for each show from transaction table.
$demo = DB::table('theater_setting')->select('row_seats_selling_price','row')->where('show_id',$value->id)->get();
foreach ($demo as $key => $val) {
$categoryArr[$val->row]=$val->row_seats_selling_price;
}
$demo4 = DB::table('theater_setting')->select('row_seats_selling_price','row')->where('show_id',$value->id)->get();
$demo3 = DB::table('transactions')->where('show_id',$value->id)->select('selected_seats','userid')->get();
for($p=0;$p<count($demo3);$p++)
{
$arr = explode(',', substr($demo3[$p]->selected_seats,0,-1));
$trans[] = $demo3[$p]->userid;
foreach ($arr as $k => $v)
{
$seats[$demo3[$p]->userid][]=$v;
}
}
foreach ($seats as $user_id=>$v)
{
for ($h=0; $h < count($v); $h++)
{
$e = explode(" ", $v[$h]);
$p = $e[0];
$demo_array[$p][$user_id][] = $v[$h];
}
$users = DB::table('users')->where('id',$user_id)->get();
}
return view('Backend.NewReportByShowsCategory2')->with([
's1'=>$s1,'shows1'=>$shows1,'demo'=>$demo,'categoryArr'=>$categoryArr,'demo3'=>$demo3,'demo4'=>$demo4,'demo_array'=>$demo_array]);
}
else
{
return view('Backend.NewReportByShowsCategory2')->with([
's1'=>$s1]);
}
}
}
I am getting the following error:
Object of class stdClass could not be converted to string
There is alternative way:
DB::table('shows')->where('show_date', 'REGEXP', Carbon\Carbon::now()->toDateString())->get();
You could convert show_date to a DATE and compare it with the current date -
$s_test = DB::table('shows')->whereRaw('DATE(show_date)=CURRENT_DATE')->get()
However, here's the regex query for selecting rows with a particular date (the current date in this case),
DB::table('shows')->whereRaw("show_date REGEXP '". Carbon\Carbon::now()->toDateString() . "'")->get()

Loop and AND conditional clause

I have had a hard time to get my head around this little piece of code.
protected function compressLowest($lowest){
$result = array();
$result['morning'] = array();
$result['afternoon'] = array();
$result['evening'] = array();
$result['allDay'] = array();
$type = $this->prices->getCondType();
$lastDate = 0;
$i = array();
$i['morning'] = $i['afternoon'] = $i['evening'] = $i['allDay'] = 0;
foreach($lowest as $date => $prices){
foreach($prices as $range => $price) {
if($this->isNextDay($date, $result[$range][$i[$range]]['to']) && $result[$range][$i[$range]]['price'] == $price){
$result[$range][$i[$range]]['to'] = $date;
} else {
$i[$range] = count($result[$range]);
$result[$range][] = array();
$result[$range][$i[$range]]['from'] = $date;
$result[$range][$i[$range]]['to'] = $date;
$result[$range][$i[$range]]['price'] = $price;
$result[$range][$i[$range]]['destime']=$this->arr['destime'];
$result[$range][$i[$range]]['deptime']=$this->arr['deptime'];
$result[$range][$i[$range]]['flight']=$this->arr['flight'];
}
}
$lastDate = $date;
}
//print_r($result);exit();
return $result;
}
And IsNextDay is checked as follows
protected function isNextDay($next, $day){
if($next - $day == 86400){ //60*60*24 = 86400
return true;
} else {
return false;
}
}
I can't figure out what is
isNextDay($date, $result[$range][$i[$range]]['to']) && $result[$range][$i[$range]]['price'] == $price) supposed to mean (the $day thing)?
in the if conditional clause of the second for-loop in the above function. Thank you if you could help me understand.
UPDATE
*Sorry I hadn't read it carefully until I discovered there was ) after the result[][]['to']... thanks for your concern.*
For the source code above, I always have a notice of UNDEFINED OFFSET 0. How to fix this bug-to-be ?
for your Undefined Offset 0 at the if line some index evaluates to 0 and the array you are using that index on does not have an element at that index.
For instance (I won't list all the possibilities) if $range is 0 and $result[0] is non-existent.

Select lowest price from database row and ignore null or 0

I have a database called prices and there are 12 columns lets say.
comp1, comp2, comp3, comp4, comp5, comp6 and so on.
I then want to run a query to find the lowest price stored in that row that matches an id, however I think it is treating null as lowest value as I am not getting the correct answer.
Anyway around this? or am i doing this wrong?
$query = "SELECT * FROM Prices WHERE id =$id" or die(mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$comp1= $row['comp1'];
$comp2= $row['comp2'];
$comp3= $row['comp3'];
$comp4= $row['comp4'];
$comp5= $row['comp5'];
$comp6= $row['comp6'];
$comp7= $row['comp7'];
$comp8= $row['comp8'];
$comp9= $row['comp9'];
$comp10= $row['comp10'];
$comp11= $row['comp11'];
$comp12= $row['comp12'];
$min = array( $comp1, $comp2, $comp3, $comp4, $comp5, $comp6, $comp7, $comp8, $comp8, $comp10, $comp11, $comp12);
echo min($min);
}
If you call array_filter() on the array before calling min(), you will purge anything that evaluates to false, including null and 0.
For example: $min = min(array_filter($min));
Try:
$min = array( $comp1, $comp2, $comp3, $comp4, $comp5, $comp6, $comp7, $comp8, $comp8, $comp10, $comp11, $comp12);
$min = array_filter($min);
echo min($min);
From a comment in http://php.net/manual/en/function.min.php:
I've modified the bugfree min-version to ignore NULL values (else it returns 0).
<?php
function min_mod () {
$args = func_get_args();
if (!count($args[0])) return false;
else {
$min = false;
foreach ($args[0] AS $value) {
if (is_numeric($value)) {
$curval = floatval($value);
if ($curval < $min || $min === false) $min = $curval;
}
}
}
return $min;
}
?>
Try this:
$query = "SELECT * FROM Prices WHERE id =$id" or die(mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$i= 0;
foreach ($row as $val) {
if ($i == 0) {
$tmpMin = $val;
} else {
if ($tmpMin < $val) {
$val = $tmpMin;
}
}
}
unset($tmpMin);
echo $tmpMin;
}

Categories