PHP passing date to SQLServer - php

I have the following SQL procedure which works on SQL Server Management studio when I execute it
USE [DatabaseName]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[getRegisterSummaryReport]
#registerID = -1,
#StartBusinessDate = '1900-01-01 00:00:00',
#EndBusinessDate = '3000-01-01 00:00:00'
SELECT 'Return Value' = #return_value
GO
what I want now is to pass the StartBusinessDate and the EndBusinessDate from a PHP function ( sorry I'm very new to PHP) .
here's what I had but for some reason I get false as a respond ( I think I'm not using the proper way to pass the date to my SQL Server).
public static function getRegisterSummary($registerId, $startBusinessDate, $endBusinessDate, $dbConnection){
$date_start = '1900-01-01 00:00:00';
$date_end = '3000-01-01 00:00:00';
if($startBusinessDate == "") $startBusinessDate = date('Y-m-d G:i:s', $date_start); // if startBusinessDate is "" I want the replace it with date_start
if($endBusinessDate == "") $endtBusinessDate = date('Y-m-d G:i:s', $date_end);
$sql = "exec [database1].[dbo].[getRegisterSummaryReport] #registerId = {$registerId}, #startBusinessDate = '{$startBusinessDate}', #endBusinessDate = '{$endBusinessDate}'";
$results = $dbConnection->query($sql);
if($results){
return $results;
}
return false;
}
Thank you

Ok This is embarrassing!!
first of all I changed the syntax to this
if($startBusinessDate == "") $startBusinessDate = date('1900-01-01');
if($endBusinessDate == "") $endBusinessDate = date('3000-01-01');
for some reason this worked with me and passed the correct value unlike when I added
date('Y-m-d G:i:s', $date_start);
Also I made a mistake in
if($endBusinessDate == "") $endtBusinessDate = date('Y-m-d G:i:s', $date_end);
I added t after $endtBusinessDate :(

Related

Randomize timing by either adding or subtracting it from current time in php

I am trying to seed DB table in Laravel. There is a time column which I need to have unique or at least not same for every record in that table.
Currently, I am using this; which does give the result to somewhat I am looking for but it's not complete.
mt_rand(0,23).":".str_pad(mt_rand(0,59), 2, "0", STR_PAD_LEFT)
My issue is that the single digit time don't have a 0 in front and sec are missing. Normally, what I was planning is the below code but it game me same results over and over:
date('H:i:s', strtotime( ((srand(0,1) ? '-'.mt_rand(1,24) : '+'.mt_rand(1,24).' '.rand(0,1) ? 'minute' : 'hour')), strtotime(date('H:i:s')))),
Result is "05:30:00" always so I am confused as to what to do next.
You said you are using Laravel, so why not just use the built-in Faker library for DateTime generation?
$faker = Faker::create();
$faker->time('H:i')
From the documentation, here is the available DateTime related outputs:
unixTime($max = 'now') // 58781813
dateTime($max = 'now', $timezone = null) // DateTime('2008-04-25 08:37:17', 'UTC')
dateTimeAD($max = 'now', $timezone = null) // DateTime('1800-04-29 20:38:49', 'Europe/Paris')
iso8601($max = 'now') // '1978-12-09T10:10:29+0000'
date($format = 'Y-m-d', $max = 'now') // '1979-06-09'
time($format = 'H:i:s', $max = 'now') // '20:49:42'
dateTimeBetween($startDate = '-30 years', $endDate = 'now', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Africa/Lagos')
dateTimeInInterval($startDate = '-30 years', $interval = '+ 5 days', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Antartica/Vostok')
dateTimeThisCentury($max = 'now', $timezone = null) // DateTime('1915-05-30 19:28:21', 'UTC')
dateTimeThisDecade($max = 'now', $timezone = null) // DateTime('2007-05-29 22:30:48', 'Europe/Paris')
dateTimeThisYear($max = 'now', $timezone = null) // DateTime('2011-02-27 20:52:14', 'Africa/Lagos')
dateTimeThisMonth($max = 'now', $timezone = null) // DateTime('2011-10-23 13:46:23', 'Antarctica/Vostok')
amPm($max = 'now') // 'pm'
dayOfMonth($max = 'now') // '04'
dayOfWeek($max = 'now') // 'Friday'
month($max = 'now') // '06'
monthName($max = 'now') // 'January'
year($max = 'now') // '1993'
century // 'VI'
timezone // 'Europe/Paris'
While #leek's answer is probably better considering you're using Laravel, a more generic way of getting what you need is the following:
$dt = new DateTime();
var_dump($dt->format('H:i:s'));
However, this will not be unique enough if you're running the script more than once a second. And of course, it will (potentially) not be unique if you run it over more than 1 day.

How to convert ISO time inside DateTime to local time?

I create a DateTime object like this
$timestamp = new DateTime('2018-04-23T07:01:05.146000+00:00');
$timestampSql = $messageTimestamp->format('Y-m-d H:i:s');
I then insert the $timestampSql into a timestamp field in my mysql table. But the problem is, that the mysql thinks that this time and date is in whatever timezone the mysql server is, and doesn't realize, that it is in fact originating from an ISO time.
So basically, I need to somehow make sure the ->format outputs the timestamp converted to the current timezone the server is set to.
Here is a way you can easily switch a timezone using the dateTime Object:
function convertDate($dateTime){
$utc = 'UTC';
$newTimZone = 'TimeZone';
$newDateTime = new DateTime($dateTime, new DateTimeZone($utc));
$newDateTime->setTimezone(new DateTimeZone($newTimZone));
return $newDateTime->format('Y-m-d H:i:s');
}
Please check below function for server and user time zone
$time_diff = get_timezone_offset('America/New_York');
if(! function_exists('get_timezone_offset'))
{
/*get time differ user and server */
function get_timezone_offset($remote_tz, $origin_tz = null) {
if($origin_tz === null) {
if(!is_string($origin_tz = date_default_timezone_get())) {
return false; // A UTC timestamp was returned -- bail out!
}
}
$origin_dtz = new DateTimeZone($origin_tz);
$remote_dtz = new DateTimeZone($remote_tz);
$origin_dt = new DateTime("now", $origin_dtz);
$remote_dt = new DateTime("now", $remote_dtz);
$offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
$offset = $offset/60;
return $offset;
}
}
$current_date = date("Y-m-d h:i:sa");
$new_date = $this->time_differction($current_date,$time_diff);
if(! function_exists('time_differction'))
{
/*Return new date and time as per user time zone */
function time_differction($date_time, $time_diff){
$time = strtotime($date_time);
$time = $time - ($time_diff * 60 );
$date = date("Y-m-d H:i:s", $time);
return $date;
}
}

assigning a value to a passed parameter in a function

sqlsrv_prepare requires query parameters to be passed by reference. How do I pass values to a function and assign a value to it? Below example, if I pass a value to the function and try to set the referenced value nothing is returned. If I assign the referenced variable a value outside of the function it returns data using those values even though I assign them something else in the function.
$getNotesSQL = "SELECT pat_id as PAT_ID, note_id as NOTE_ID, CONVERT(char(10), UPDATE_DATE, 120) as UPDATE_DATE ";
$getNotesSQL .= "FROM CLARITY.dbo.HNO_INFO";
$getNotesSQL .= " WHERE ip_note_type_c = ? ";
$getNotesSQL .= " AND (UPDATE_DATE >= ? AND UPDATE_DATE <= ?)";
if (!$getNotes = sqlsrv_prepare($clarity, $getNotesSQL, array(&$noteType, &$startDate, &$endDate))) {
echo "getNotesSQL couldn't be prepared\n";
die(print_r(sqlsrv_errors(), true));
}
$note_type = strval(1);
$start_date = "2017-05-29";
$end_date = "2017-07-11";
/**
$noteType = strval(1);
$startDate = "2017-07-01";
$endDate = "2017-07-11";
*/
function getNotes($getNotes, $note_type, $start_date, $end_date) {
$noteType = $note_type;
$startDate = $start_date;
$endDate = $end_date;
if (!sqlsrv_execute($getNotes)) {`enter code here`
echo "getNotes Couldn't be executed\n";
die(print_r(sqlsrv_errors(), true));
}
$noteArray = array();
$iii=0;
while ($row = sqlsrv_fetch_array($getNotes, SQLSRV_FETCH_ASSOC)) {
// print_r($row);
$noteArray[$iii] = $row;
$iii++;
}
echo "In getNote Function iii: (" . $iii .")\n";
print_r($noteArray);
return $noteArray;
}
$fetchedNotes = getNotes($getNotes, $note_type, $start_date, $end_date);
print_r($fetchedNotes);
I'm not entirely sure on the reasoning behind it - I think it might have something to do with scope - but you need to pass-by-reference the query parameter variables into the function too.
So something like this:
function getNotes($getNotes, $note_type, $start_date, $end_date, &$noteType, &$startDate, &$endDate){
//perform query
}
Now that's a little ugly and quite annoying to maintain should the number of query parameters change. However you could group the values and query parameters into arrays and pass the arrays into the function. Like this:
function getNotes($getNotes, $values, $params){
foreach($params as $key => &$param){
$param = $values[$key];
}
// sqlsrv_execute
}
$values = [$note_type, $start_date, $end_date];
$params = [&$noteType, &$startDate, &$endDate];
$fetchedNotes = getNotes($getNotes, $values, $params);
I tried something similar to this on my users table, to test it, and it seems to work okay.

php add method incorrectly working

I'm in the process of learning PHP and i'm having some trouble. My function is returning the "milestones" with the same date they were plugged in with. I believe I am using the add() method incorrectly. Thankyou.
PHPplayground: http://www.tehplayground.com/#cARB1wjth
$milestones = null;
$milestones = createMilestone($milestones, true, 10, "15-1-1", "birthday" );
var_dump( $milestones );
function createMilestone($milestones, $forward, $days, $startDate, $milestoneName ){
if ( is_string($startDate)){
$date = DateTime::createFromFormat("Y-m-d", $startDate );
}else if(is_array($startDate) ){
$date = $startDate["date"];
}else{
$date = $startDate;
};
$daysInterval = DateInterval::createFromDateString($days);
if ($forward){
$date->add($daysInterval);
}else{
$date->sub($daysInterval);
}
$milestones[$milestoneName]['date'] = $date;
return $milestones;
}
You need to use :
$daysInterval = DateInterval::createFromDateString($days . ' days');
See the doc here for DateInterval and that page for the diverse date formatting (called relative format) you can use.
And BTW, if you give a DateTime like "15-1-1", the correct format is not "Y-m-d" but "y-m-d" (lowercase 'y')

Laravel 5 ORM update request, like date_add

I beg to excuse me for my poor english.
So, I have Laravel 5 ORM, and i need to make request that should add date to some rows, like MySQL DATE_ADD. Input is single date interval and array of id's, output is rows of database, that was changed by adding date interval. Ideally, it should be one ORM request. I know that it is possible to use "bad" way and get all rows, update it in a code, and insert to database, but imho it's not good.
I hope answer will be link to some help site or some code if it's does not complicate you. Thanks for your attention!
public function update($id)
{
$user_id = Auth::user()->id;
$rep_task = RepTask::find($id);
$cl_task = \Request::has('json') ? json_decode(\Request::input('json'),true) : \Request::all();
$ids = [];
$task_id = $rep_task->task_id;
$rep_tasks = RepTask::where('task_id', '=', $task_id)
->select('id')
->get();
$new_date = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT, $cl_task['new_date']);
$selected_task_date = date_create_from_format(self::DATE_MYSQL_FORMAT, $rep_task->start_date);
$diff = date_diff($selected_task_date, $new_date);
if(\Request::has('json'))
{
$ids = [1,2,3]; //this for easy understanding
DB::table('rep_task')
->whereIn('id', $ids)
->update(['start_date' => DB::raw('DATE_ADD(start_date, INTERVAL ' . $diff->d . ' DAY)')]);
$out_json = ['updated' => $ids];
return json_encode($out_json, JSON_UNESCAPED_UNICODE);
}
else
{
$start_date = 0;
$end_date = 0;
if (!isset($cl_task['name']) || !isset($cl_task['text']))
return "{'error':'columns are not defined'}";
if (isset($cl_task['start_date']) && isset($cl_task['end_date']))
{
$dt = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT, $cl_task['start_date']);
$start_date = $dt->format(self::DATE_MYSQL_FORMAT);
$dt = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT,$cl_task['end_date']);
$end_date = $dt->format(self::DATE_MYSQL_FORMAT);
}
$rep_task->name = $cl_task['name'];
$rep_task->text = $cl_task['text'];
$rep_task->start_date = $start_date;
$rep_task->end_date = $end_date;
$rep_task->users_id = $user_id;
$rep_task->save();
}
$user_id = Auth::user()->id;
$tasks = Task::getAllTasksByUserFullcalendar($user_id);
return view(
'task.index',
[
'tasks' => $tasks
]
);
}

Categories