cannot insert the right values into table - php

I have a database named user_job_apply(id, job_id, postby_id, applier_id, flag, flag_wall, time_apply).
The "time_apply" type in my database was set to :datetime
My problem is that the following piece of code inserts everything suceesfully in my databe, but it does not insert the value for $timeString. When I look in my database it shows 0000-00-00 00:00:00. Any idea what is the problem here?
I have tested by echoing $timeString and it displays date and time with success, but i cannot pass it into my database. Any idea how to fix this?
<?php
// the next two values comes from a form
$the_job_code = mysql_real_escape_string($_POST['jobid']);
$the_postedby = mysql_real_escape_string($_POST['postedby']);
// use it to get current time from user's computer
$timeString= '
<script language="javascript">
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd="0"+dd
}
if(mm<10) {
mm="0"+mm
}
today = mm+"/"+dd+"/"+yyyy + " " +today.getHours() + ":" + today.getMinutes()+":" + today.getSeconds();
document.write(today);
</script> ';
mysql_query("INSERT INTO `user_job_apply` VALUES ('', '$the_job_code', '$the_postedby ', '$session_user_id', '1', '1', '$timeString') ");
?>

Maybe you need use MySQL date format, like 'YYYY-MM-DD'?

It can be because of your Mysql localization settings and the dateformat, try what stepozer said 'YYYY-MM-DD'
today = yyyy+"/" +mm+"/"+dd+ " " +today.getHours() + ":" + today.getMinutes()+":" + today.getSeconds();
or you can just insert the current date and time directly on your sql using the function NOW()
mysql_query("INSERT INTO `user_job_apply` VALUES ('', '$the_job_code', '$the_postedby ', '$session_user_id', '1', '1', NOW()) ");

The "today" variable defined at the bottom of your Javascript block is not defined in a format compatible with MySQL.
It should be defined like this:
today = yyyy+"-"+mm+"/"+dd+" "+today.getHours()+":"+today.getMinutes()+":"+today.getSeconds();
Like this it will output in the format needed by MySQL to save in a "datetime" field.
EDIT:
The above solution only solves part of your problem.
The main problem here is that this code runs on the server-side after the form is submitted.
You should move the javascript block to the html file where the form resides (after the form) and write the "today" variable to a hidden form input called "timeString".
After submission you should receive this variable through the post:
$timeString = mysql_real_escape_string($_POST['timeString']);
EDIT 2:
First you need to create a hidden form input inside your form:
<input type="hidden" name="timeString" id="timeStringInput">
You need to copy the following block to your html file, right after the end of the form ():
<script language="javascript">
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd="0"+dd
}
if(mm<10) {
mm="0"+mm
}
today = yyyy+"/"+mm+"/"+dd+" "+today.getHours()+":"+today.getMinutes()+":"+ today.getSeconds();
document.getElementById('timeStringInput').value = today;
</script>
On the PHP file, replace the $timeString assignment (complete block) with:
$timeString = mysql_real_escape_string($_POST['timeString']);

Related

Sending and receiving multiple dates via AJAX to PHP

I hope I am able to explain what I'm trying to do properly, but I am trying to use AJAX to pass (using POST) quite a number of Dates to PHP file, to do checks if dates are valid (e.g. 31-FEB, 31-Apr).
I am not sure how many dates there will be, there are 12 entry boxes, maximum case 12 dates, minimum case 1. So the number of dates passed to the PHP file could be anything.
I want to be able to "roll" through (using numbers 0 1 2 like in an array) all the dates (and their D, M, Y) inside the PHP file, and also "roll" through dates passed back to the JS from PHP.
Jquery
var DAT = {}; //is such a declaration valid for an array?
k=0;
for(x=1;x<=12;x++)
{ I = "#ED" + x;
d= $(I).children('.dd').val();
m= $(I).children('.mmm').val();
y= $(I).children('.yyyy').val();
c= date_chk(d,m,y); //returns '1' if date ok
if(c==1) //Date OK
{ DATE[k] = [d,m,y];
alert(DATE[k][0]+" "+DATE[k][1]+" "+DATE[k][2]);
k++;
}
}
AJ.onreadystatechange = function(){
if((AJ.readyState == 4) && (AJ.status == 200))
{ var PH_RP = AJ.responseText;
alert("PHP REPLY:: " + PH_RP);
var DATE_Lst = JSON.parse(PH_RP);
alert("DATE1 Day::" + DATE_Lst.DT[0][0] + "DATE1 Month::" + DATE_Lst.DT[0][1] +"DATE1 Year::" + DATE_Lst.DT[0][2] );
alert("DATE2 Day::" + DATE_Lst.DT[1][0] + "DATE2 Month::" + DATE_Lst.DT[1][1] +"DATE2 Year::" + DATE_Lst.DT[1][2] );
}
var para = "DATESS=" + DATE; //? how do I send the whole stack of dates to the PHP file?
AJ.open("POST", "PHP/4_PHP_Check_Dates.php", true);
AJ.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
AJ.send(para);
Here is the PHP file::
$LOGARRY['DT'] = $_POST['DATESS'];
or
$LOGARRY['DT1'] = $_POST['DATESS'][1];
$LOGARRY['DT2'] = $_POST['DATESS'][2];
echo json_encode($LOGARRY);
Thanks.. any help appreciated
If you just want to check if a date is valid, you do not need the roundtrip to PHP, you can do that right in Javascript.
Detecting an "invalid date" Date instance in JavaScript
You asked how to send an array to PHP via XMLHttpRequest.
Since I avoid JQuery like the plague, I cannot really comment on your code, but here is a simple way to send X dates to you PHP script:
Three things:
it is simple (no errorchecking etc)
it used GET. Feel free to make it into a POST.
Open your javascript console to see the result.
<html>
<body>
<script>
// I assume you have an array with strings that might represent dates, like:
// dates[0] = "2022-10-09";
// dates[1] = "2021-13-09";
// ....
// dates[19] = "I am surely not a date";
// dates[20] = "2000-01-05";
var dates = [];
dates[0] = "2022-10-09";
dates[1] = "2021-13-09";
dates[2] = "I am surely not a date";
dates[3] = "2000-01-05";
var myTestDates = JSON.stringify(dates);
var myReq = new XMLHttpRequest();
myReq.addEventListener("load", reqListener);
var url = "dateChecker.php?dates=" + encodeURIComponent(myTestDates);
url += "&rand=" + Math.random();
myReq.open("GET", url , true);
myReq.send();
function reqListener () {
let passeddates = JSON.parse(this.responseText);
console.log(passeddates);
}
</script>
</body>
</html>
And the PHP script (named dateChecker.php):
<?php
$passedDates = json_decode( $_GET["dates"] );
$checkedDates = [];
foreach ($passedDates as $oneDate){
$d = DateTime::createFromFormat('Y-m-d', $oneDate);
$valid = ($d && $d->format('Y-m-d') === $oneDate) ? "valid" : "not valid";
$checkedDates[] = $oneDate . " is {$valid}";
}
echo json_encode($checkedDates);
?>

Reverse counter FlipClock with PHP-MySQL

I want to use flipclock for the reverse counter. The timer should start from hh:mm:ss (eg, 19:40:46) to 00:00:00.
Below is the code
var clock;
$(document).ready(function() {
// Grab the current date
var currentDate = new Date();
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date(currentDate.getFullYear() + 1, 0, 1);
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
// Instantiate a coutdown FlipClock
clock = $('.dw_clock').FlipClock(diff, {
clockFace: 'DailyCounter',
countdown: true,
showSeconds: true
});
});
I don't want the date. Also, the time values should get fetched from MySQL and are different for different users when they log in. From PHP-MySQL, I have:
function timeToPlay(&$smarty){
$sqlStr = "select timediff('24:00:00', time(taken_on)) as timeRemaining,
hour(timediff('24:00:00', time(taken_on))) as hour,
minute(timediff('24:00:00', time(taken_on))) as minute,
second(timediff('24:00:00', time(taken_on))) as second
FROM profile_sicc_exer_score where user_id=".$_SESSION['user_id']."
order by id desc limit 1";
$sqlQuery = mysql_query($sqlStr) or die(mysql_error()."<hr>".$sqlStr);
if ( mysql_num_rows($sqlQuery) ) {
$timeToPlayNext = mysql_fetch_assoc($sqlQuery);
$smarty->assign("timeRemaining",$timeToPlayNext['timeRemaining']);
$smarty->assign("hour",$timeToPlayNext['hour']);
$smarty->assign("minute",$timeToPlayNext['minute']);
$smarty->assign("second",$timeToPlayNext['second']);
}
}
From the above code, I get the values of (example)
$timeRemaining = 19:40:46
$hour = 19
$minute = 40
$second = 46
How do I use the values in the above Flipclock code which is javascript/jquery...
For flipClock, you have to change the clockFace to "HourlyCounter", so it doesn't show the date.
After that, having the php variables, you can "echo" them into the javascript code, for example, at the end of the webpage, you can put:
<script>
clock.setTime(<?php echo $hour*3600+$minute*60+$second; ?>);
</script>
You can always put it in an "onload" function or something like that, but it should work fine with that.
You didn't left any details about the actual html page where the counter is showing, so I can't help you further this.
Good luck!

How to count time from when user load a page/form until they submit it?

I have a quiz page with some questions (multiple choice, true-false). In the results after the submit of page i want to show something like this:
Started on Tuesday, 1 January 2013, 04:09 AM
Completed on Tuesday, 1 January 2013, 04:10 AM
Time taken 47 secs
Grade 7 out of a maximum of 10 (65%)
i dont know how to count start time and end time to show the above results and how to count the time from when user's load a page until they submit the form.
i'm new and i need your advise. i dont have problem if the problem solved with php or javascript or jquery
You can do something like this and the start and end timestamps will be submitted along with the form. You could then do the calculations with PHP.
var form = document.getElementById("form");
window.onload = function() {
var start = document.createElement("input");
start.type = "hidden";
start.name = "start";
start.value = +new Date()/1000; //unix timestamp
form.appendChild(start);
};
form.onsubmit = function() {
var stop = document.createElement("input");
stop.type = "hidden";
stop.name = "stop";
stop.value = +new Date()/1000;
form.appendChild(stop);
};
Ok here is my solution:
1- user starts the quiz and you put the time in $_SESSION var
$_SESSION['quiztime']=date("Y-m-d H:i:s");
2-User finishes the test and you check the time passed (this example is in minutes you don't have to divide it by 60 if you need seconds)
$to_time = strtotime(date("Y-m-d H:i:s"));
$from_time = strtotime($_SESSION['quiztime']);
echo round(abs($to_time - $from_time) / 60,2). " minutes";
I'd put the time started in a cookie or session, and then once they complete it, just subtract that time from the current time -- That's the time taken!
It may look like this:
Quiz page:
session_start();
$_SESSION['startTime'] = time();
// This is where the quiz would be displayed
Quiz results page:
session_start();
$totalTime = time() - $_SESSION['startTime'];
echo $totalTime;
My "bullet-proofer" solution would be to store the start time on the server, (in the session) associated with a unique id generated per-form and kept in an hidden field.
This way you prevent the user from tampering with it (he might change the unique id, but in that case the form would be invalid) and you don't depend on the client having javascript enabled.
<?php
$form_uuid = uniqid();
$_SESSION['quiz_start_time'][$form_uuid] = time();
Then, in your form, put something like this:
<input type="hidden" name="form_id" value="<?php print $form_uuid; ?>">
And in the form submit handler:
<?php
$form_uuid = $_POST['form_id'];
if (!isset($_SESSION['quiz_start_time'][$form_uuid])) {
// The user is trying to do something nasty (or the session just expired)
// Return something like a 400 error
}
else {
$start_time = $_SESSION['quiz_start_time'][$form_uuid];
// Do other form processing here..
}

JavaScript / PHP: Get a Client's Month and Day with JS, Pass the Values to PHP Variable

I want to get day and month from a client's computer, and then pass it to PHP in two separate variables, which would result in something like this:
$day_num = 11;
$month_num = 12;
I need JavaScript function and PHP function to be separate files, and I need to pass the value
not in the URL.
I would be grateful for a bit of help from an expert!
Javascript:
If you are using jQuery gettting it back to the server is super easy (if you do it without, see: How to make an AJAX call without jQuery?):
<script language="javascript">
var date = new Date(),
month = date.getMonth(),
day = date.getDate();
$.post('path-to-php.php', { day: day, month: month});
</script>
PHP:
<?php
var_dump($_POST['day']);
var_dump($_POST['month']);
?>
Edit:
path-to-php.php is the filename of your php file. It can be absolute or relative, depending on your application. If you wanted to post it to the same file, you could use this instead of path-to-php.php: <?php echo $_SERVER['PHP_SELF'];?>
With javascript:
function executeAjax() {
var date = new Date(),
var month = date.getMonth(),
var day = date.getDate();
var url="daymonth.php?month="+month+"&day="+day;
var objX=new XMLHttpRequest();
objX.open("GET",url,false);
objX.send(null);
var response=objX.responseText;
}
daymonth.php
<?php
$day=$_GET['day'];
$month=$_GET['month'];
?>

JQuery and PHP Date difference

I am using a jquery date picker and also setting a date through php date('Y-m-D') functions. Both of them give different date for today. Jquery picker fills the field with the date that is one day ahead of php date(). Here is the function for jquery. I need jquery to show same date for today as php.
<script type="text/javascript" charset="utf-8">
var $j = jQuery.noConflict();
$j(function()
{
// initialise the "Select date" link
$j('#date-pick')
.datePicker(
// associate the link with a date picker
{
createButton:false,
startDate: '01/01/1970',
endDate: (new Date()).asString()
//endDate:<?php echo date('y-m-d'); ?>
}
).bind(
// when the link is clicked display the date picker
'click',
function()
{
updateSelects($j(this).dpGetSelected()[0]);
$j(this).dpDisplay();
return false;
}
).bind(
// when a date is selected update the SELECTs
'dateSelected',
function(e, selectedDate, $td, state)
{
updateSelects(selectedDate);
}
).bind(
'dpClosed',
function(e, selected)
{
updateSelects(selected[0]);
}
).val(new Date().asString()).trigger('change');
var updateSelects = function (selectedDate)
{
var selectedDate = new Date(selectedDate);
if(selectedDate != "Invalid Date")
{
$j('#d').val(selectedDate.getDate());
$j('#m').val(selectedDate.getMonth()+1);
$j('#y').val(selectedDate.getFullYear());
}
}
// listen for when the selects are changed and update the picker
// default the position of the selects to today
var today = new Date();
updateSelects(today.getTime());
});
</script>
jQuery uses the client computer's date while php uses the server's date. They're basically different if you haven't set the default timezone in php. Take a look at this:
http://php.net/manual/en/function.date-default-timezone-set.php
You can set the default timezone in php.ini file located on the PHP main directory (Eg. PHP5.4)
As for the using of the server's date in the datepicker:
A quick google search lead me to this: how to display server side dates in jquery datepicker?
basically what they have done is creating a new date based on the current timestamp:
$timestamp = strtotime("2012-08-02");
minDate: new Date('<?php echo $timestamp; ?>');
DO NOT TRUST THE CLIENTS DATE AND TIME
These values can be altered at a whim.
Just use them on advisement.
Besides Javascript is there to enhance the users experience (i.e. make it more interactive). But at the end of the day you will have to pick up the pieces it you do not validate and verify the data you get from the client

Categories