Wednesday, 24 February 2016

PHP MYSQL - DATE and TIME functions


TIMEDIFF( )

Synopsis

TIMEDIFF(time, time)
This function returns the time difference between the two times given. Although the arguments may be given in time or date-and-time format, both arguments must be of the same datatype. This function is available as of Version 4.1.1 of MySQL.
SELECT appointment AS Appointment, NOW( ) AS Now,
       TIMEDIFF(appointment, NOW( )) AS 'Time Remaining'
   FROM appointments
   WHERE rec_id='3783';
+--------------------+--------------------+----------------+
| Appointment        | Now                | Time Remaining |
+--------------------+--------------------+----------------+
| 2005-01-11 10:30:00| 2005-01-11 22:28:09| 12:01:51       |
+--------------------+--------------------+----------------+
TIME( )

Synopsis

TIME(time)
This function returns the time from a given string or column containing date and time data. This function is available as of Version 4.1.1 of MySQL.
SELECT TIME(NOW( )) , NOW( );
+-------------+---------------------+
| TIME(NOW( )) | NOW( )                |
+-------------+---------------------+
| 21:14:20    | 2005-01-11 21:14:20 |
+-------------+---------------------+
SYSDATE( )

Synopsis

SYSDATE( )
This function returns the system date. It will return the date and time in ayyyy-mm-dd hh:mm:ss format, but will return the data in a yyyymmddformat if it's used as part of a numeric calculation. This function is an alias for the NOW( ) function.
SELECT SYSDATE( );
+---------------------+
| SYSDATE( )           |
+---------------------+
| 2004-05-09 18:44:51 |
+---------------------+
SUBTIME( )

Synopsis

SUBTIME(datetime, datetime)
This function returns the date and time for the given string or column, decreased by the time given as the second argument (d hh:mm:ss). If a negative number is given, the time is added and the function is the equivalent of ADDTIME(). This function is available as of Version 4.1.1 of MySQL.
SELECT NOW( ) AS Now,
       SUBTIME(NOW( ), '1:00:00.00') AS 'Hour Ago';
+---------------------+---------------------+
| Now                 | Hour Ago            |
+---------------------+---------------------+
| 2005-01-12 00:54:59 | 2005-01-11 23:54:59 |
+---------------------+---------------------+
Notice that the hour was decreased by one, and because the time is just after midnight, the function causes the date to be altered by one day, as well. To decrease the date, add the number of days before the time (separated by a space) like so:
 SELECT NOW( ) AS Now,
        SUBTIME(NOW( ), '30 0:0.0') AS 'Thirty Days Ago';
+---------------------+---------------------+
| Now                 | Thirty Days Ago     |
+---------------------+---------------------+
| 2005-01-12 00:57:04 | 2004-12-13 00:57:04 |
+---------------------+---------------------+
SUBDATE( )

Synopsis

SUBDATE(date, INTERVAL value type)
Use this function to subtract a time interval from the results of a date or timedatatype column. If a negative value is given, the interval is added and is equivalent to the ADDDATE( ) function. This is an alias for the DATE_SUB( )function. See DATE_ADD( ) for a table of incremental types.
SELECT SUBDATE(NOW( ), INTERVAL 1 DAY)
          AS 'Yesterday',
       SUBDATE(NOW( ), INTERVAL -1 DAY)
          AS 'Tomorrow';
+---------------------+---------------------+
| Yesterday           | Tomorrow            |
+---------------------+---------------------+
| 2004-05-09 16:11:56 | 2004-05-11 16:11:56 |
+---------------------+---------------------+
As of Version 4.1 of MySQL, for subtracting days the second argument of the function may simply be the number of days (i.e., just 1 instead of INTERVAL 1DAY).

TIMESTAMPDIFF( )

TIMESTAMPDIFF(interval, datetime, datetime)
This function returns the time difference between the two times given but only for the interval being compared. The intervals accepted are the same as those for the TIMESTAMPADD( ) function. This function is available as of Version 5 of MySQL.
SELECT NOW( ) AS Today,
       TIMESTAMPDIFF(DAY, NOW( ), LAST_DAY(NOW( )))
          AS 'Days Remaining in Month';
+---------------------+-------------------------+
| Today               | Days Remaining in Month |
+---------------------+-------------------------+
| 2016-02-24 07:03:41 | 4                       |
+---------------------+-------------------------+
TIMESTAMP( )

Synopsis

TIMESTAMP(date, time)
This function returns date and time (in yyyy-mm-dd hh:mm:ss format) from a given string or column containing date and time data, respectively. If only the date or only the time is given, the function will return zeros for the missing parameters. This function is available as of Version 4.1.1 of MySQL.
SELECT TIMESTAMP(appt_date, appt_time)
   FROM appointments LIMIT 1;
+---------------------------------+
| TIMESTAMP(appt_date, appt_time) |
+---------------------------------+
| 2005-01-15 10:30:00             |
+---------------------------------+

uniqid() - Four ways to generate unique id by PHP

 Four ways to generate unique id by PHP


1. Using uniqid() function

<?php
//creates a unique id with the 'about' prefix$a uniqid(about);
echo 
$a;
echo 
"<br>";
//creates a longer unique id with the 'about' prefix$b uniqid (abouttrue);
echo 
$b;
echo 
"<br>";
//creates a unique ID with a random number as a prefix - more secure than a static prefix $c uniqid (rand(), true);
echo 
$c;
echo 
"<br>";
//this md5 encrypts the username from above, so its ready to be stored in your database$md5c md5($c);
echo 
$md5c;
echo 
"<br>";
?>

2. Using current time + IP style

<?php
//You can also use $stamp = strtotime ("now"); But I think date("Ymdhis") is easier to understand.$stamp date("Ymdhis");$ip $_SERVER['REMOTE_ADDR'];$orderid "$stamp-$ip";$orderid str_replace(".""""$orderid");
echo(
$orderid);
echo 
"<br>";
?>

3. Generate custom length unique id

<?php
//set the random id length $random_id_length 10;
//generate a random id encrypt it and store it in $rnd_id $rnd_id crypt(uniqid(rand(),1));
//to remove any slashes that might have come $rnd_id strip_tags(stripslashes($rnd_id));
//Removing any . or / and reversing the string $rnd_id str_replace(".","",$rnd_id); $rnd_id strrev(str_replace("/","",$rnd_id));
//finally I take the first 10 characters from the $rnd_id $rnd_id substr($rnd_id,0,$random_id_length);

echo 
"Random Id: $rnd_id" ;
echo 
"<br>";
?>

4. Generate XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX style unique id, (8 letters)-(4 letters)-(4 letters)-(4 letters)-(12 letters)

<?php
// Generate Guid function NewGuid() {
    
$s strtoupper(md5(uniqid(rand(),true)));
    
$guidText =
        
substr($s,0,8) . '-' .
        
substr($s,8,4) . '-' .
        
substr($s,12,4). '-' .
        
substr($s,16,4). '-' .
        
substr($s,20);
    return 
$guidText;
}
// End Generate Guid
$Guid NewGuid();
echo 
$Guid;
echo 
"<br>";
?>

Friday, 5 February 2016

PHP Get last 12 months from now

<?php
$months = array();
for ($i = 1; $i <= 12; $i++) {
    $months[] = date("Ym", strtotime( date( 'Y-m-01' )." -$i months"));
}
print_r($months);
?>

Tuesday, 12 January 2016

How to put HTML data into header of tcpdf

As @vinzcoco says, you must extend TCPDF to achieve what you want. Here is a simple improvement that I think it could be useful for you:
class MyTCPDF extends TCPDF {

    var $htmlHeader;

    public function setHtmlHeader($htmlHeader) {
        $this->htmlHeader = $htmlHeader;
    }

    public function Header() {
        $this->writeHTMLCell(
            $w = 0, $h = 0, $x = '', $y = '',
            $this->htmlHeader, $border = 0, $ln = 1, $fill = 0,
            $reseth = true, $align = 'top', $autopadding = true);
    }

}
Now, once you've got your MyTCPDF object available, you just need to do this to set the HTML header content:
$mytcpdfObject->setHtmlHeader('<table>...</table>');
and the HTML content won't be hardcoded into the Header() method (more flexible for you).

PHP Equvilent base64_encode with javascript code

<script type="text/javascript">
function base64_encodeRsync (data) {
  var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
    ac = 0,
    enc = "",
    tmp_arr = [];

  if (!data) {
    return data;
  }

  do { // pack three octets into four hexets
    o1 = data.charCodeAt(i++);
    o2 = data.charCodeAt(i++);
    o3 = data.charCodeAt(i++);

    bits = o1 << 16 | o2 << 8 | o3;

    h1 = bits >> 18 & 0x3f;
    h2 = bits >> 12 & 0x3f;
    h3 = bits >> 6 & 0x3f;
    h4 = bits & 0x3f;

    // use hexets to index into b64, and append result to encoded string
    tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  } while (i < data.length);

  enc = tmp_arr.join('');

  var r = data.length % 3;

  return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);

}

</script>
We can decode this encrypted data in php by passing that value to  base64_decode function.

Tuesday, 29 December 2015

A PHP function to sum values in associative arrays


For a new project, I needed to combine two or more associative arrays and sum the values of any keys that exist in common. I was a little surprised to find that there wasn’t a built-in function to do this in PHP. So I wrote my own. It can accept any number of arrays as arguments, and goes through each array one key at a time, comparing the keys to those in an output array. Where the keys match, the values are summed. If the key does not exist in the output array, it’s appended to it.


The function returns an array that contains all of the unique keys in the input arrays.
<?php
function array_mesh() {
// Combine multiple associative arrays and sum the values for any common keys
// The function can accept any number of arrays as arguments
// The values must be numeric or the summed value will be 0

// Get the number of arguments being passed
$numargs = func_num_args();

// Save the arguments to an array
$arg_list = func_get_args();

// Create an array to hold the combined data
$out = array();

// Loop through each of the arguments
for ($i = 0; $i < $numargs; $i++) {
$in = $arg_list[$i]; // This will be equal to each array passed as an argument

// Loop through each of the arrays passed as arguments
foreach($in as $key => $value) {
// If the same key exists in the $out array
if(array_key_exists($key, $out)) {
// Sum the values of the common key
$sum = $in[$key] + $out[$key];
// Add the key => value pair to array $out
$out[$key] = $sum;
}else{
// Add to $out any key => value pairs in the $in array that did not have a match in $out
$out[$key] = $in[$key];
}
}
}

return $out;
}
$a = array('abc' => '100.000', 'def' => '50', 'ghi' => '25', 'xyz' => '10');
$b = array('abc' => '100.333', 'def' => '75', 'ghi' => '50', 'jkl' => '25');
$c = array('abc' => '100.111', 'def' => '75', 'ghi' => '50', 'uvw' => '5');

echo "<pre>";
print_r(array_mesh($a, $b, $c));
echo "</pre>";
?>
OUTPUT:
Array
(
    [abc] => 300.444
    [def] => 200
    [ghi] => 125
    [xyz] => 10
    [jkl] => 25
    [uvw] => 5
)

Wednesday, 2 December 2015

PHP array_insert_after() & array_insert_before()

I need to insert a key/value at a certain position in an associative array. It seems like a common issue. I was surprised to discover there wasn't a straightforward answer. Here is the method I created. If you know of a more efficient method, please let me know in the comments.
/*
 * Inserts a new key/value before the key in the array.
 *
 * @param $key
 *   The key to insert before.
 * @param $array
 *   An array to insert in to.
 * @param $new_key
 *   The key to insert.
 * @param $new_value
 *   An value to insert.
 *
 * @return
 *   The new array if the key exists, FALSE otherwise.
 *
 * @see array_insert_after()
 */
function array_insert_before($key, array &$array, $new_key, $new_value) {
  if (array_key_exists($key, $array)) {
    $new = array();
    foreach ($array as $k => $value) {
      if ($k === $key) {
        $new[$new_key] = $new_value;
      }
      $new[$k] = $value;
    }
    return $new;
  }
  return FALSE;
}
 
/*
 * Inserts a new key/value after the key in the array.
 *
 * @param $key
 *   The key to insert after.
 * @param $array
 *   An array to insert in to.
 * @param $new_key
 *   The key to insert.
 * @param $new_value
 *   An value to insert.
 *
 * @return
 *   The new array if the key exists, FALSE otherwise.
 *
 * @see array_insert_before()
 */
function array_insert_after($key, array &$array, $new_key, $new_value) {
  if (array_key_exists($key, $array)) {
    $new = array();
    foreach ($array as $k => $value) {
      $new[$k] = $value;
      if ($k === $key) {
        $new[$new_key] = $new_value;
      }
    }
    return $new;
  }
  return FALSE;
}