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

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()

Related

Find records between two time slots in php

i have time slots like
$timeslot = ['09:00-10:00', .... '23:00-00:00', '00:00-01:00'];
I have records with updated time as 23:15:00, 23:30:00, 00:15:00, 09:15:00 etc.
What i'm trying to find is the sum of records between each of the $timeslot. I'm not considering what day got updated, only time i'm looking for.
i tried with:-
$data = ['23:15:00', '23:30:00', '00:15:00', '09:15:00'];
foreach($data as $val) {
$cnt = 0;
foreach($timeslot as $slots) {
$slot = explode("-", $slots);
if( (strtotime($val) > strtotime($slot[0])) && (strtotime($val) <= strtotime($slot[1])) ) {
$up_time[$slot[0] . '-' . $slot[1]] = $cnt++;
}
}
}
echo '<pre>';print_r($up_time);echo '</pre>';
The expected output is:-
09:00-10:00 = 1
23:00-00:00 = 2
00:00-01:00 = 1
Strtotime is not required since your time can be compared as strings.
This code works as you expected.
$data = ['23:15:00', '23:30:00', '00:15:00', '09:15:00'];
$timeslot = ['09:00-10:00', '23:00-00:00', '00:00-01:00'];
$up_time = array();
foreach ($data as $val) {
$myTime = substr($val, 0, 5);
foreach ($timeslot as $slot) {
$times = explode("-", $slot);
if (substr($times[1], 0, 3) == "00:") {
$times[1] = "24:" . substr($times[1], 3);
}
if ($myTime >= $times[0] && $myTime <= $times[1]) {
if (!isset($up_time[$slot])) {
$up_time[$slot] = 1;
} else {
$up_time[$slot]++;
}
}
}
}
echo '<pre>';
print_r($up_time);
echo '</pre>';
The if with 'substr' is needed because for midnight you have '00' and not '24' so the computer thinks is an empty set (such as hours bigger then 23 and smaller then 0).
Comparison is made between string because bigger time is also a bigger string since you use 2 digits for hours.
You need to count equal slots so you need an array with an element for each slot and increment if duplicate or create an element if not found (the condition '!isset').
Update for modification request
$data = ['23:15:00', '23:30:00', '00:15:00', '09:15:00'];
// added unused slot 8:00-9:00
$timeslot = ['08:00-09:00','09:00-10:00', '23:00-00:00', '00:00-01:00'];
$up_time = array();
// new initialization
foreach ($timeslot as $slot) {
$up_time[$slot] = 0;
}
foreach ($data as $val) {
$myTime = substr($val, 0, 5);
foreach ($timeslot as $slot) {
$times = explode("-", $slot);
if (substr($times[1], 0, 3) == "00:") {
$times[1] = "24:" . substr($times[1], 3);
}
if ($myTime >= $times[0] && $myTime <= $times[1]) {
$up_time[$slot]++; // simplified
}
}
}

How to grade scores in php

I'm trying to grade some scores according to highest average obtained..
Here's my scripts
$scores_AND_ID = 'M2377O=100,M2727B=100,M5821K=100,M7492F=97.75,M7973O=96,M3487I=94,M7969O=93.13,M1452V=92.5,M4653O=92.38,M4158J=92.25,M2881A=89.38,M6112S=28.63,';
$out_score = chop($scores_AND_ID, ',');
$rr2 = explode(",", $out_score);
$array_un = array_unique($rr2);
foreach ($array_un as $key => $value) {
if ($value == "") {
continue;
}
$postion = positionNumbers($key);//1st,2nd,3rd function
$sec = explode("=", $value);
rsort($sec);
$stdntID = $sec[0]; //Student number
$stdntAV = $sec[1]; //Student Average
mysql_query("UPDATE score_table SET grade='$postion' WHERE avg='$stdntAV' ");
}
I'm using foreach key to assign grade position but isn't working properly.
Here's my result
Here's what I need to achieve.
1. 100---1st
2. 100---1st
3. 100---1st
4. 98---4th
5. 89.5--5th
6. 89---6th
7. 89---6th
8. 80---8th
Thanks Guys
I think the code you want is this:
<?php
$scores_AND_ID = 'M7492F=97.75,M7973O=96,M3487I=94,M2377O=100,M2727B=100,M5821K=100,M7969O=93.13,M1452V=92.5,M4653O=92.38,M4158J=92.25,M2881A=89.38,M6112S=28.63,';
// Gets all of the entries from the source string
$scores_array = array_unique(array_filter(explode(',', $scores_AND_ID)));
// Sets up an associative array of values (student id => score)
$score_map = [];
foreach ($scores_array as $record) {
[ $student_id, $score ] = explode('=', $record);
$score_map[$student_id] = $score;
}
// Ensure values are sorted numerically descending
uasort($score_map, function ($a, $b) {
if ($a > $b) {
return -1;
}
if ($a == $b) {
return 0;
}
return 1;
});
// Gets the maximum value from the scores
$previous_score = max(array_values($score_map));
$rank = 1;
$incrementer = 0;
foreach ($score_map as $student => $score) {
// If the score hasn't changed from it's previous value
// we increment a counter instead of the rank
if ($score == $previous_score) {
$incrementer++;
// Once it's changed, we update the rank based on the incrementer
// and then reset the incrementer
} else {
$rank += $incrementer;
$incrementer = 1;
}
$previous_score = $score;
// Updating database is left as an exercise to the reader
}
You should not update your records if grade is already set. If you print your query instead of executing it you will see that you set grade 1st, then you overwrite it with 2nd and then with 3rd.

PHP evaluating the content of an array

I am trying to evaluate the content of an array. The array contain water temperatures submitted by a user.
The user submits 2 temperaures, one for hot water and one for cold water.
What I need is to evaluate both array items to find if they are within the limits, the limits are "Hot water: between 50 and 66", "Cold water less than 21".
If either Hot or Cold fail the check flag the Status "1" or if they both pass the check flag Status "0".
Below is the code I am working with:
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$SeqWaterArray new(array);
$SeqWaterArray = array("58", "21");
foreach($SeqWaterArray as $key => $val) {
$fields[] = "$field = '$val'";
if($key == 0) {
if($val < $row_WaterTemp['HotMin'] || $val > $row_WaterTemp['Hotmax']) {
$Status = 1;
$WaterHot = $val;
} else {
$Status = 0;
$WaterHot = $val;
}
}
if($key == 1) {
if($val > $row_WaterTemp['ColdMax']) {
$Status = 1;
$WaterCold = $val;
} else {
$Status = 0;
$WaterCold = $val;
}
}
}
My question is:
When I run the script the array key(0) works but when the array key(1) is evaluted the status flag for key(1) overrides the status flag for key0.
If anyone can help that would be great.
Many thanks for your time.
It seems OK to me, exept for the values at limit, and you can simplify
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$SeqWaterArray = array("58", "21");
$Status = array() ;
foreach($SeqWaterArray as $key => $val) {
if($key == 0) {
$Status = ($val >= $row_WaterTemp['HotMin'] && $val <= $row_WaterTemp['Hotmax']) ;
$WaterHot = $val;
} else if($key == 1) {
$Status += ($val >= $row_WaterTemp['ColdMax']) ;
$WaterCold = $val;
}
}
If one fails, $Status = 1, if the two tests failed, $Status = 2, if it's ok, $Status = 0.
<?php
// this function return BOOL (true/false) when the condition is met
function isBetween($val, $min, $max) {
return ($val >= $min && $val <= $max);
}
$coldMax = 20; $hotMin = 50; $hotMax = 66;
// I decided to simulate a test of more cases:
$SeqWaterArray['john'] = array(58, 30);
$SeqWaterArray['martin'] = array(34, 15);
$SeqWaterArray['barbara'] = array(52, 10);
foreach($SeqWaterArray as $key => $range) {
$flag = array();
foreach($range as $type => $temperature) {
// here we fill number 1 if the temperature is in range
if ($type == 0) {
$flag['hot'] = (isBetween($temperature, $hotMin, $hotMax) ? 0 : 1);
} else {
$flag['cold'] = (isBetween($temperature, 0, $coldMax) ? 0 : 1);
}
}
$results[$key]['flag'] = $flag;
}
var_dump($results);
?>
This is the result:
["john"]=>
"flag"=>
["hot"]=> 1
["cold"]=> 0
["martin"]=>
"flag" =>
["hot"]=> 1
["cold"]=> 0
["barbara"]=>
"flag" =>
["hot"]=> 0
["cold"]=> 0
I don't think that you need a foreach loop here since you are working with a simple array and apparently you know that the first element is the hot water temperature and the second element is the cold water temperature. I would just do something like this:
$row_WaterTemp['HotMin'] = 50;
$row_WaterTemp['HotMax'] = 66;
$row_WaterTemp['ColdMax'] = 21;
$SeqWaterArray = array(58, 21);
$waterHot = $SeqWaterArray[0];
$waterCold = $SeqWaterArray[1];
$status = 0;
if ($waterHot < $row_WaterTemp['HotMin'] || $waterHot > $row_WaterTemp['HotMax']) {
$status = 1;
}
if ($waterCold > $row_WaterTemp['ColdMax']) {
$status = 1;
}
You can combine the if statements of course. I separated them because of readability.
Note that I removed all quotes from the numbers. Quotes are for strings, not for numbers.
You can use break statement in this case when the flag is set to 1. As per your specification the Cold water should be less than 21, I have modified the code.
<?php
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$row_WaterTemp['ColdMax'] = "21";
$SeqWaterArray = array("58", "21");
foreach($SeqWaterArray as $key => $val) {
$fields[] = "$key = '$val'";
if($key == 0) {
if($val < $row_WaterTemp['HotMin'] || $val > $row_WaterTemp['Hotmax']) {
$Status = 1;
$WaterHot = $val;
break;
} else {
$Status = 0;
$WaterHot = $val;
}
}
if($key == 1) {
if($val >= $row_WaterTemp['ColdMax']) {
$Status = 1;
$WaterCold = $val;
break;
} else {
$Status = 0;
$WaterCold = $val;
}
}
}
echo $Status;
?>
This way it would be easier to break the loop in case if the temperature fails to fall within the range in either case.
https://eval.in/636912

Change date from database into an array

I am wondering how to the change date from this
Db -> holiday -> holidayDate (type date) = 2015-01-01, 2015-01-03, 2015-02-19, 2015-03-21, 2015-04-03, 2015-05-01, 2015-05-14, 2015-05-16, 2015-06-02, 2015-07-17, 2015-07-18, 2015-08-17, 2015-09-24, 2015-10-14, 2015-12-25
Here is the code
$sql = "select * from holiday order by holidayDate ";
//echo $sql;
$ambil_data = mysql_query($sql);
if ($data = mysql_fetch_array($ambil_data))
{
$tglLibur2 = $data['holidayDate'];
}
else
{
echo mysql_error();
}
function selisihHari($tglAwal, $tglAkhir)
{
$tglLibur = array("'".$tglLibur2."'"); <= i just want to get this array from db
$pecah1 = explode("-", $tglAwal);
$date1 = $pecah1[2];
$month1 = $pecah1[1];
$year1 = $pecah1[0];
$pecah2 = explode("-", $tglAkhir);
$date2 = $pecah2[2];
$month2 = $pecah2[1];
$year2 = $pecah2[0];
$jd1 = GregorianToJD($month1, $date1, $year1);
$jd2 = GregorianToJD($month2, $date2, $year2);
$selisih = ($jd2 - $jd1);
$libur1 = 0;
$libur2 = 0;
$libur3 = 0;
for($i=1; $i<=$selisih; $i++)
{
$tanggal = mktime(0, 0, 0, $month1, $date1+$i, $year1);
$tglstr = date("Y-m-d", $tanggal);
if (in_array($tglstr, $tglLibur))
{
$libur1++;
}
if ((date("N", $tanggal) == 7))
{
$libur2++;
}
if ((date("N", $tanggal) == 6))
{
$libur3++;
}
}
return $selisih-$libur1-$libur2-$libur3;
}
into this
$tglLibur = array("2015-01-01","2015-01-03","2015-02-19",
"2015-03-21","2015-04-03","2015-05-01","2015-05-14","2015-05-16",
"2015-06-02","2015-07-17","2015-07-18","2015-08-17","2015-09-24",
"2015-10-14","2015-12-25");
First of all your function selisihHari doesn't have access to the variable tglLibur2 you're using inside it. So I'm thinking you didn't post your full code here. But what you're looking for can be done with the following code:
$tglLibur = array()
foreach($tglLibur2 as $date){
$tglLibur[] = $date;
}
But what you're doing in your fetch code doesn't make sense. You keep overwriting the same variable. To change that do the following:
$tglLibur2 = array();
if ($data = mysql_fetch_array($ambil_data))
{
$tglLibur2[] = $data['holidayDate'];
}
This should give you the array you're looking for. That way you can get rid of your function all together.
Assuming that you aren't looping through each row and that $data['holidayDate'] is a string of dates, comma delimited, just change:
$tglLibur2 = $data['holidayDate'];
to
$tglLibur[] = explode(', ', $data['holidayDate']);

Show SINGLE RECORD with newest expiration date

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

Categories