I am trying to get data from some particular range of dates,
<?php
function index_finder()
{
$strStart = '2021-01-02';
$strEnd = '2021-08-28';
$dteStart = new DateTime($strStart);
$dteEnd = new DateTime($strEnd);
$dteDiff = $dteStart->diff($dteEnd);
$date = $dteDiff->format("%m month\n");
if ($date > 6)
{
$curl = 'https://localhost:9200/studio-.'$strStart'.,studio-.'$strEnd'./_search?pretty';
print $curl;
}
}
if date range is more then 6 months, then need to call this curl with start and end date,
I am trying to insert the startdate and end date in the url.
Kindly help me out to pass the dates in the url.
Thanks in advance
Replace this :
$curl = 'https://localhost:9200/studio-.'$strStart'.,studio-.'$strEnd'./_search?pretty';
By this :
$curl = 'https://localhost:9200/studio-' . $strStart . ',studio-' . $strEnd . '/_search?pretty';
Related
My error message in codeigniter framework:
A Database Error Occurred
Error Number: 1140
In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'hms.rooms.id'; this is incompatible with sql_mode=only_full_group_by
SELECT `rooms`.*, count(room_no) as total_rooms FROM `rooms` WHERE `room_type_id` = '10'
Filename: D:/Installed_Apps/OpenServer/OpenServer/domains/hms.loc/system/database/DB_driver.php
Line Number: 691
Why is there such an error and how to eliminate it? In what there can be a problem in the code?
In these functions, something is wrong or everything is normal?
function check_availability($check_in,$check_out,$adults,$kids,$room_type_id){
$query = '?date_from='.$check_in.'&date_to='.$check_out.'&adults='.$adults.'&kids='.$kids.'&room_type=';
$CI =& get_instance();
if($check_in==$check_out){
$check_out = date('Y-m-d', strtotime($check_out.'+ 1 day'));
}
$CI->db->where('id',1);
$settings = $CI->db->get('settings')->row_array();
$CI->db->where('id',$room_type_id);
$CI->db->select('room_types.*,base_price as price');
$room_type = $CI->db->get('room_types')->row_array();
//echo '<pre>'; print_r($room_type);die;
$CI->db->where('room_type_id',$room_type_id);
$CI->db->select('rooms.*,count(room_no) as total_rooms');
$rooms = $CI->db->get('rooms')->row_array();
$total_rooms = $rooms['total_rooms'];
//echo '<pre>'; print_r($rooms);die;
$begin = new DateTime($check_in);
$end = new DateTime($check_out);
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach($period as $dt){
$date = $dt->format( "Y-m-d" );
$dayno = $dt->format( "N" );
$day = $dt->format( "D" );
$day = strtolower($day);
///echo $date;die;
//check for room block period
if($date >= $settings['room_block_start_date'] && $date <=$settings['room_block_end_date'])
{
$block_message = "Sorry.. No Room Available Between ".date('d/m/Y',strtotime($settings['room_block_start_date']))." to ".date('d/m/Y',strtotime($settings['room_block_end_date']))." ";
$CI->session->set_flashdata('error', $block_message);
redirect('');
}
$CI->db->where('O.room_type_id',$room_type_id);
$CI->db->where('R.date',$date);
$CI->db->select('R.*,');
$CI->db->join('orders O', 'O.id = R.order_id', 'LEFT');
$orders = $CI->db->get('rel_orders_prices R')->result_array();
//echo '<pre>'; print_r($orders);die;
//echo $total_rooms;die;
if($total_rooms > 0){
//echo count($orders);die;
if(count($orders) >= $total_rooms){
$CI->session->unset_userdata('booking_data');
$CI->session->unset_userdata('coupon_data');
$CI->session->set_flashdata('error', "Sorry.. This Dates Between Rooms Not Available Please Try With Another Date Or Room");
redirect('front/book/index'.$query);
}else{
continue; // continue loop
}
}else{
$CI->session->unset_userdata('booking_data');
$CI->session->unset_userdata('coupon_data');
$CI->session->set_flashdata('error', "Sorry.. This Dates Between Rooms Not Available Please Try With Another Date Or Room");
redirect('front/book/index'.$query);
}
}
return;
}
function check_availability_ajax($check_in,$check_out,$adults,$kids,$room_type_id){
$query = '?date_from='.$check_in.'&date_to='.$check_out.'&adults='.$adults.'&kids='.$kids.'&room_type=';
$CI =& get_instance();
if($check_in==$check_out){
$check_out = date('Y-m-d', strtotime($check_out.'+ 1 day'));
}
$CI->db->where('id',1);
$settings = $CI->db->get('settings')->row_array();
$CI->db->where('id',$room_type_id);
$CI->db->select('room_types.*,base_price as price');
$room_type = $CI->db->get('room_types')->row_array();
//echo '<pre>'; print_r($room_type);die;
$CI->db->where('room_type_id',$room_type_id);
$CI->db->select('rooms.*,count(room_no) as total_rooms');
$rooms = $CI->db->get('rooms')->row_array();
$total_rooms = $rooms['total_rooms'];
//echo '<pre>'; print_r($rooms);die;
$begin = new DateTime($check_in);
$end = new DateTime($check_out);
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach($period as $dt){
$date = $dt->format( "Y-m-d" );
$dayno = $dt->format( "N" );
$day = $dt->format( "D" );
$day = strtolower($day);
if($date >= $settings['room_block_start_date'] && $date <=$settings['room_block_end_date'])
{
$block_message = "Sorry.. No Room Available Between ".date('d/m/Y',strtotime($settings['room_block_start_date']))." to ".date('d/m/Y',strtotime($settings['room_block_end_date']))." ";
return $block_message;
}
$CI->db->where('O.room_type_id',$room_type_id);
$CI->db->where('R.date',$date);
$CI->db->select('R.*,');
$CI->db->join('orders O', 'O.id = R.order_id', 'LEFT');
$orders = $CI->db->get('rel_orders_prices R')->result_array();
//echo $total_rooms;die;
if($total_rooms > 0){
if(count($orders) > $total_rooms){
$CI->session->unset_userdata('booking_data');
$CI->session->unset_userdata('coupon_data');
return 'Sorry.. This Dates Between Rooms Not Available Please Try With Another Date Or Room';
}else{
continue; // continue loop
}
}else{
$CI->session->unset_userdata('booking_data');
$CI->session->unset_userdata('coupon_data');
return 'Sorry.. This Dates Between Rooms Not Available Please Try With Another Date Or Room';
}
}
return 1;
}
Here is my Book.php controller code where I use that functions:
function index()
{
//echo '<pre>'; print_r($_GET);
//check availbilty
//get_invoice_number();
$this->session->unset_userdata('booking_data');
$this->session->unset_userdata('coupon_data');
$data['page_title'] = lang('make_reservation');
$data['meta_description'] = $this->setting->meta_description;
$data['meta_keywords'] = $this->setting->meta_keywords;
$data['banners'] = $this->homepage_model->get_banners();
$data['testimonials'] = $this->homepage_model->get_testimonials(); // get 6 testimonials
$data['room_types'] = $this->homepage_model->get_room_types_all();
$data['taxes'] = $this->homepage_model->get_taxes();
if(!empty($_GET['room_type'])){
$data['services'] = $this->homepage_model->get_paid_services($_GET['room_type']);
}
//echo '<pre>'; print_r($data['services']);
if(empty($_GET['room_type'])){
$this->render('book/room_types', $data);
}else{
check_availability($_GET['date_from'],$_GET['date_to'],$_GET['adults'],$_GET['kids'],$_GET['room_type']);
$data['room_type'] = $this->homepage_model->get_room_type($_GET['room_type']);
$this->render('book/view', $data);
}
}
you are facing this problem because of the ONLY_FULL_GROUP_BY option in the MYSQL so kindly set,
SET GLOBAL sql_mode=(SELECT REPLACE(##sql_mode,'ONLY_FULL_GROUP_BY',''));
to solve the issue.
SQL query including aggregate functions like COUNT() or SUM() etc. always have a GROUP BY clause in it. Which specifies the other non-grouped columns in the final resultset.
In you query the following remarks are noted:
You have specified rooms.* which is not recommended while grouping.
You may mention specific columns while grouping, and specify those columns in the GROUP BY clause too.
For example,
SELECT
Count(product_tb.product_id),
product_tb.`name`,
product_tb.details
FROM
`product_tb`
WHERE
product_tb.product_id = 1
GROUP BY
product_tb.`name`,
product_tb.details
How to calculate a date before 10 days of every month end ?Am using codeigniter platform.
I need to check whether a date is within 10 days before the end of every month.
Please help
You can try using date_modify function for example see this php documentation
http://php.net/manual/en/datetime.modify.php
i need to check whether a date is within10 days before the end of a month
function testDate($date) {
$uDate = strtotime($date);
return date("m", $uDate) != date("m", strtotime("+10 days", $uDate));
}
echo testDate("2016-03-07") ? "Yes" :"No"; // No
echo testDate("2016-03-27") ? "Yes" :"No"; // Yes
you can create a library with this
class Calculate_days{
function __construct() {
parent::__construct();
}
function calculate( $to_day = date("j") ){
$days_month = date("t");
$result = (int) $days_month - $to_day;
if( $result <= 10){
$result = array("type" => TRUE, "missing" => $result . 'days');
return $result;
}
else{
$result = array("type" => FASLE, "missing" => $result . 'days');
return $result;
}
}
}
controller.php
function do_somthing(){
$this->load->library('Calculate_days');
$result = $this->Calculate_days->calculate(date("j"));
var_dump($result);
}
I made a previous post that was too vague. I've done a lot of research and think I can be more specific.
while (!feof($file_handle))
{
$loansinfo = fgetcsv($file_handle);
// Make sure we only check data for the game we posted
if($loansinfo[0]==$ID) {
$referenceDate = $WantedDate;
$fromDate = "$loansinfo[5]";
$toDate = "$loansinfo[6]";
// Convert dates to timestamps (strings to integers)
$referenceTimestamp = strtotime( $referenceDate );
$fromTimestamp = strtotime( $fromDate );
$toTimestamp = strtotime( $toDate );
$isBetween = $referenceTimestamp >= $fromTimestamp and $referenceTimestamp <= $toTimestamp;
//refuse booking
echo('<script type="text/javascript">alert("Game Already Booked");</script>');
exit;
}
}
// otherwise execute save code
Problem is, I always get 'Game already booked'. Why?
Sample CSV file data as requested:
ID, GameName,GameCost, DaysRequested, Total, ReservationStart, DateEnd
5,Pinball, 3.99,7, 27.99, 01/01/2015, 08/01/2015
Though it should be said that the form requires date entry as YYYY-MM-DD. I have java script that does the conversion.
I've seen this one! Try this:
while (!feof($file_handle)) {
$loansinfo = fgetcsv($file_handle);
if($loansinfo[0]==$ID){
$FromDate = "$loansinfo[5]";
$ToDate ="$loansinfo[6]";
if (strtotime($DateBorrowedFrom) <= strtotime($WantedDate)) {
if(strtotime($ToDate) >= strtotime($WantedDate)){
$CantBook = True;
}
}
else {
if (strtotime($DateBorrowedFrom) <= strtotime($DateTo)) {
$CantBook= true;
}
}
}
}
fclose($file_handle);
if($CantBook = true){
echo('<script type="text/javascript">alert("Game is already Booked");</script>');
}
else{
//Saving the booking
From the look of your code, you are not checking the result of $isBetween.
Here is a modified version that will get you a lot closer, assuming your dates are formatted correctly.
while (!feof($file_handle))
{
$loansinfo = fgetcsv($file_handle);
// Make sure we only check data for the game we posted
if($loansinfo[0]==$ID) {
$referenceDate = $WantedDate;
$fromDate = "$loansinfo[5]";
$toDate = "$loansinfo[6]";
// Convert dates to timestamps (strings to integers)
$referenceTimestamp = strtotime( $referenceDate );
$fromTimestamp = strtotime( $fromDate );
$toTimestamp = strtotime( $toDate );
$isBetween = $referenceTimestamp >= $fromTimestamp and $referenceTimestamp <= $toTimestamp;
if($isBetween == true) {
//refuse booking
echo('<script type="text/javascript">alert("Game Already Booked");</script>');
exit;
}
}
}
I'm using the v3 Google API for Youtube:
$url = 'https://www.googleapis.com/youtube/v3/search?part=id&channelId=' . $channelID . '&maxResults=50&order=date&key=' . $API_key;
I've set up a script which should give me all videos from a given channel ID. For some channels I get all videos, for some a few are missing (compared with the number of videos shown directly in Youtube), and for bigger channel I get a max. result of 488 videos despite there are more.
The pageToken is a strange thing. For example a channel has 955 videos. I get 18 pages with 50 items per page (that would be 900 videos). Some of them are playlists but if I subtract the 23 playlists I still have 877 videos. If I remove duplicates I only have 488 results! The totalResults in the JSON output shows me 975 results!?
This is my recursive function:
function fetchAllVideos($parsed_json){
$foundIds = array();
if($parsed_json != ''){
$foundIds = getVideoIds($parsed_json);
$nextPageToken = getNextPageToken($parsed_json);
$prevPageToken = getPrevPageToken($parsed_json);
if($nextPageToken != ''){
$new_parsed_json = getNextPage($nextPageToken);
$foundIds = array_merge($foundIds, fetchAllVideos($new_parsed_json));
}
if($prevPageToken != ''){
$new_parsed_json = getNextPage($prevPageToken);
$foundIds = array_merge($foundIds, fetchAllVideos($new_parsed_json));
}
}
return $foundIds;
}
I call it with $videoIds = fetchAllVideos($parsed_json); and $parsed_json is the result from the first URL which I retrieve. Can you see an error here?
Does anybody know how the number of videos are counted, which are directly shown in Youtube? Has anybody managed to get a full list which correspond to the number in Youtube?
This script goes through selecting a 60 day period at a time and retrieves the results for it, then adds it to the existing data array. By doing this there are no limitations to how many videos are allowed, though it may take some time to trawl larger YouTube channels with a couple thousand videos. Make sure you set the API_KEY, timezone, username, start date (should begin before the first video on the channel), and period (set by default to 60 * 60 * 24 * 60, which is 60 days in seconds. This will need to be lower if the frequency of videos is higher than about 50 for 60 days.) (5184000 seconds).
*All of this is commented within the script.
date_default_timezone_set("TIMEZONE");
//youtube api key
$API_KEY = "YOUR API KEY";
function search($searchTerm,$url){
$url = $url . urlencode($searchTerm);
$result = file_get_contents($url);
if($result !== false){
return json_decode($result, true);
}
return false;
}
function get_user_channel_id($user){
global $API_KEY;
$url = 'https://www.googleapis.com/youtube/v3/channels?key=' . $API_KEY . '&part=id&forUsername=';
return search($user,$url)['items'][0]['id'];
}
function push_data($searchResults){
global $data;
foreach($searchResults['items'] as $item){
$data[] = $item;
}
return $data;
}
function get_url_for_utc_period($channelId, $utc){
//get the API_KEY
global $API_KEY;
//youtube specifies the DateTime to be formatted as RFC 3339 formatted date-time value (1970-01-01T00:00:00Z)
$publishedAfter = date("Y-m-d\TH:i:sP",strval($utc));
//within a 60 day period
$publishedBefore_ = $utc + (60 * 60 * 24 * 60);
$publishedBefore = date("Y-m-d\TH:i:sP",$publishedBefore_);
//develop the URL with the API_KEY, channelId, and the time period specified by publishedBefore & publishedAfter
$url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&key=' . $API_KEY . '&maxResults=50&channelId=' . $channelId . '&publishedAfter=' . urlencode($publishedAfter) . '&publishedBefore=' . urlencode($publishedBefore);
return array("url"=>$url,"utc"=>$publishedBefore_);
}
//the date that the loop will begin with, have this just before the first videos on the channel.
//this is just an example date
$start_date = "2013-1-1";
$utc = strtotime($start_date);
$username = "CHANNEL USERNAME NOT CHANNEL ID";
//get the channel id for the username
$channelId = get_user_channel_id($username);
while($utc < time()){
$url_utc = get_url_for_utc_period($channelId, $utc);
$searchResults = search("", $url_utc['url']);
$data = push_data($searchResults);
$utc += 60 * 60 * 24 * 60;
}
print "<pre>";
print_r($data);
print "</pre>";
//check that all of the videos have been accounted for (cross-reference this with what it says on their youtube channel)
print count($data);
https://gdata.youtube.com/feeds/api/users/USERNAME_HERE/uploads?max-results=50&alt=json&start-index=1 did the trick. It's a JSON feed where you have to loop until you get less than 50 results.
Edit:
This should be the script I used:
ini_set('max_execution_time', 900);
function getVideos($channel){
$ids = array();
$start_index = 1;
$still_have_results = true;
if($channel == ""){
return false;
}
$url = 'https://gdata.youtube.com/feeds/api/users/' . $channel . '/uploads?max-results=50&alt=json&start-index=' . $start_index;
$json = file_get_contents($url);
$obj = json_decode($json);
while($still_have_results){
foreach($obj->feed->entry as $video){
$video_url = $video->id->{'$t'};
$last_pos = strrpos($video_url, '/');
$video_id = substr($video_url, $last_pos+1, strlen($video_url) - $last_pos);
array_push($ids, $video_id);
}
$number_of_items = count($obj->feed->entry);
$start_index += count($obj->feed->entry);
if($number_of_items < 50) {
$still_have_results = false;
}
$url = 'https://gdata.youtube.com/feeds/api/users/' . $channel . '/uploads?max-results=50&alt=json&start-index=' . $start_index;
$json = file_get_contents($url);
$obj = json_decode($json);
}
return $ids;
}
$videoIds = getVideos('youtube');
echo '<pre>';
print_r($videoIds);
echo '</pre>';
Now I made a test, but I didn't gathered 100% of the videos. Nevertheless, the best option I came up with.
Trying to setup a page that auto updates based on the users date/time.
Need to run a promotion for 2 weeks and each day it needs to change the displayed image.
Was reading through http://www.thetricky.net/php/Compare%20dates%20with%20PHP to get a better handle on php's time and date functions.Somewhat tricky to test, but I basically got stuck on:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date() = $dateA){
echo 'todays message';
}
else if(date() = $dateB){
echo 'tomorrows message';
}
?>
I know the above function is wrong as its setup, but I think it explains what I am aiming for.
Time is irrelevant, it needs to switch over at midnight so the date will change anyway.
You seem to need this:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date('Y-m-d') == $dateA){
echo 'todays message';
} else if(date('Y-m-d') == $dateB){
echo 'tomorrows message';
}
?>
you want
<?php
$today = date('Y-m-d')
if($today == $dateA) {
echo 'todays message';
} else if($today == $dateB) {
echo 'tomorrows message';
}
?>
I would go a step back and handle it via file names. Something like:
<img src=/path/to/your/images/img-YYYY-MM-DD.jpg alt="alternative text">
So your script would look something like this:
<img src=/path/to/your/images/img-<?php echo date('Y-m-d', time()); ?>.jpg alt="alternative text">
If you're going to do date calculations, I'd recommend using PHP's DateTime class:
$promotion_starts = "2012-07-16"; // When the promotion starts
// An array of images that you want to display, 0 = the first day, 1 = the second day
$images = array(
0 => 'img_1_start.png',
1 => 'the_second_image.jpg'
);
$tz = new DateTimeZone('America/New_York');
// The current date, without any time values
$now = new DateTime( "now", $tz);
$now->setTime( 0, 0, 0);
$start = new DateTime( $promotion_starts, $tz);
$interval = new DateInterval( 'P1D'); // 1 day interval
$period = new DatePeriod( $start, $interval, 14); // 2 weeks
foreach( $period as $i => $date) {
if( $date->diff( $now)->format("%d") == 0) {
echo "Today I should display a message for " . $date->format('Y-m-d') . " ($i)\n";
echo "I would have displayed: " . $images[$i] . "\n"; // echo <img> tag
break;
}
}
Given that the promotion starts on 07-16, this displays the following, since it is now the second day of the promotion:
Today I should display a message for 2012-07-17 (1)
I would have displayed: the_second_image.jpg