Working with php sessions

If you want to change the session id on each log in, make sure to use session_regenerate_id(true) during the log in process.

session_start();
session_regenerate_id(true);
?>

To forget the session start is the most common error. This must be put at the first line of code  to work properly.

Document here the code and scripts for killing session. could be on page unload or with a logout button.

I had some stuff going using the flash and a backend. If you need to check it out, its here, but I think you have the sesh stuff on lockdown. Now just need to bust out the device detector.

How to make a date formatted to insert into MySQL database using PHP

This is great, goes with the jquery ui pop up calendar datepicker. Formats the date to be inserted into mysql’s funky date field.

$my_formatted_date = date(‘Y-m-d’, strtotime($my_unformatted_date));

 

Here is a MySQL select for nothing older than 15 minutes.
select darecord, dadate from mytable where dadate > NOW() – INTERVAL 15 MINUTE

Here is how to calculate the amount time between two time entries:
SELECT TIMEDIFF(`time_in`, `time_out`)  FROM `project_timecards`

 

As stated in Date and Time Literals:

MySQL recognizes DATE values in these formats:

  • As a string in either 'YYYY-MM-DD' or 'YY-MM-DD' format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example, '2012-12-31', '2012/12/31', '2012^12^31', and '2012@12@31' are equivalent.
  • As a string with no delimiters in either 'YYYYMMDD' or 'YYMMDD' format, provided that the string makes sense as a date. For example, '20070523' and '070523' are interpreted as '2007-05-23', but '071332' is illegal (it has nonsensical month and day parts) and becomes '0000-00-00'.
  • As a number in either YYYYMMDD or YYMMDD format, provided that the number makes sense as a date. For example, 19830905 and 830905 are interpreted as '1983-09-05'.

Therefore, the string '08/25/2012' is not a valid MySQL date literal. You have four options (in some vague order of preference, without any further information of your requirements):

  1. Configure Datepicker to provide dates in a supported format using its dateFormat option:
    $( ".selector" ).datepicker({ dateFormat: "yyyy-mm-dd" });
  2. Use MySQL’s STR_TO_DATE() function to convert the string:
    INSERT INTO user_date VALUES ('', '$name', STR_TO_DATE('$date', '%m/%d/%Y'))
  3. Convert the string received from jQuery into a PHP timestamp—e.g. using strtotime():
    $timestamp = strtotime($_POST['_date']);

    and then either:

    • format the timestamp using date():
      $date = date('Y-m-d', $timestamp);
    • pass the timestamp directly to MySQL using FROM_UNIXTIME():
      INSERT INTO user_date VALUES ('', '$name', FROM_UNIXTIME($timestamp))
  4. Manually manipulate the string into a valid literal:
    $parts = explode('/', $_POST['date']); $date = "$parts[2]-$parts[0]-$parts[1]";

 

JQuery ajax form post techniques

Here is the standard ajax form post code:

$.ajax({

type: “POST”,

url: “some.php”,

data: { name: “John”, location: “Boston” }

}).done(function( msg ) {

alert( “Data Saved: ” + msg );

});

 

Here is a sweet ajax form submit with fading confirmations

While developing, you might run into the problem where you made some changes, but the browser isn’t running the new code. That is cause by caching. For a final release, you wouldn’t want to make the user have to re load all the scripts and data every time, but during development, you need to keep changing and accessing the latest scripts. There a few things you could do. Try CTR + F5 to do a refresh of the browser and cache. 

Here is a new chunk to add to this if needed to prevent caching in internet explorer. Add cache: false to the ajax method. Add a random variable to the query string. Begin to use POST from now on to prevent this.

var random = Math.floor((Math.random()*1000)+1);

$(“#submit_personalinfo_button”).click(function(d){
d.preventDefault();
$(“#area1”).fadeOut(1000);
setTimeout(function(){
$.ajax( {
type: “GET”,
url: $(“#svc_letsdolunch_personalinfoform”).attr( ‘action’ ),
cache: false,
data: $(“#svc_letsdolunch_personalinfoform”).serialize(),
success: function( response ) {
$(“#area1”).html( response ).fadeIn(1000).delay(3000).fadeOut(1000);
}
} ); }, 1000);

});

 

What about if there was an error, like the server times out, you have a typo or error in your script, or the internet is not connected. There is a way to check for these. But you have to alter the ajax call so it becomes an object that you can use.

var myajaxrequest = $.ajax({type: “POST”,   url: “mysweetscripts.php”,   data: { what: what} });

now we can call more methods on this object as so…

myajaxrequest.done(function( msg ) {alert(‘done!’)});

myajaxrequest.success(function( msg ) {alert(success!’)});<— note that this is used the same as .done(); Don’t need to use both of these in the call.

myajaxrequest.fail(function( jqXHR, textStatus, errorThrown) {
alert(‘request failed error textStatus: ‘ + textStatus + ‘…Error thrown: ‘ + errorThrown);

)});

I haven’t found a use yet for the jqXHR object, but the textStatus will hold arguments (besides null) are "timeout", "error", "abort", and "parsererror". I could check these and decide what to do in each situation. When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as “Not Found” or “Internal Server Error.” This could be useful in development, to see if there is an error in your script.

Here is some exciting stuff to look into when checking for stuff with ajax,

ifModified
Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the ‘etag’ specified by the server to catch unmodified data.

 

 $("#myform").find('select:first').change( function() {     $.ajax( {       type: "POST",       url: $("#myform").attr( 'action' ),       data: $("#myform").serialize(),       success: function( response ) {         console.log( response );       }     } );   } );

THE FORMDATA OBJECT

One of the enhancements to XMLHttpRequest is the introduction of the FormData object. With the FormData object, you can create and send a set of key/value pairs and, optionally, files using XMLHttpRequest. When using this technique, the data is sent in the same format as if you’d submitted it via the form’s submit() method with the encoding type of multipart/form-data.

FormData gives you a way to create HTML forms on-the-fly using JavaScript, and then submit them using XMLHttpRequest.send().  This is how the bad guys are making those bots that submit directly to my form actions, and trying to mess with my database. Here’s a simple example:

var formData = new FormData();
formData.append(“part_num”, “123ABC”);
formData.append(“part_price”, 7.95);
formData.append(“part_image”, somefile)

var xhr = new XMLHttpRequest();
xhr.open(“POST”, “http://some.url/”);
xhr.send(formData);