PHP and MySQL syntax: Difference between revisions

From LemonWiki共筆
Jump to navigation Jump to search
Line 25: Line 25:


=== now ===
=== now ===
==== '''human readable''' time format ====
Convert '''unix timestamp''' (the number of seconds since 1970/01/01) <--> to the '''human readable''' time format ex: {{Template:Today}} {{CURRENTTIME}}:06
Convert '''unix timestamp''' (the number of seconds since 1970/01/01) <--> to the '''human readable''' time format ex: {{Template:Today}} {{CURRENTTIME}}:06
* php: echo date("Y-m-d H:i:s", time() ); //Convert the time stamp of current time to the human readable time format. Ex: return '{{Template:Today}} {{CURRENTTIME}}:06'
* php: echo date("Y-m-d H:i:s", time() ); //Convert the time stamp of current time to the human readable time format. Ex: return '{{Template:Today}} {{CURRENTTIME}}:06' {{exclaim}} server timezone dependent
* mysql:  
* mysql: {{exclaim}} server timezone dependent
** {{kbd | key=<nowiki>SELECT NOW();</nowiki>}} Returns {{Template:Today}} {{CURRENTTIME}}:06 which mapping to {{kbd | key=<nowiki>DATETIME</nowiki>}} type<ref>[http://dev.mysql.com/doc/refman/5.1/en/datetime.html MySQL :: MySQL 5.1 Reference Manual :: 11.3.1 The DATE, DATETIME, and TIMESTAMP Types]</ref>
** {{kbd | key=<nowiki>SELECT NOW();</nowiki>}} Returns {{Template:Today}} {{CURRENTTIME}}:06 which mapping to {{kbd | key=<nowiki>DATETIME</nowiki>}} type<ref>[http://dev.mysql.com/doc/refman/5.1/en/datetime.html MySQL :: MySQL 5.1 Reference Manual :: 11.3.1 The DATE, DATETIME, and TIMESTAMP Types]</ref>
** {{kbd | key=<nowiki>SELECT NOW()+0;</nowiki>}} //2011-04-01 12:19:43 returns 20110401122023.000000
** {{kbd | key=<nowiki>SELECT NOW()+0;</nowiki>}} //2011-04-01 12:19:43 returns 20110401122023.000000
Line 48: Line 49:
** {{kbd | key=<nowiki>echo `TZ=Asia/Taipei date +\%Y-\%m-\%d\ %H:%M:%S` 2>&1</nowiki>}} or {{kbd | key=<nowiki>TZ=Asia/Taipei date +\%Y-\%m-\%d\ %H:%M:%S</nowiki>}} Returns {{Template:Today}} {{CURRENTTIME}}:06 {{exclaim}} force to use Taipei timezone
** {{kbd | key=<nowiki>echo `TZ=Asia/Taipei date +\%Y-\%m-\%d\ %H:%M:%S` 2>&1</nowiki>}} or {{kbd | key=<nowiki>TZ=Asia/Taipei date +\%Y-\%m-\%d\ %H:%M:%S</nowiki>}} Returns {{Template:Today}} {{CURRENTTIME}}:06 {{exclaim}} force to use Taipei timezone


the current '''timestamp''' ex: 1292897201
==== the current '''timestamp''' ====
ex: 1292897201
* php: {{kbd | key=<nowiki>echo time();</nowiki>}} //Return the number of seconds since 1970/01/01
* php: {{kbd | key=<nowiki>echo time();</nowiki>}} //Return the number of seconds since 1970/01/01
* php: {{kbd | key=<nowiki>echo microtime();</nowiki>}}  [http://php.net/manual/en/function.microtime.php PHP: microtime - Manual] "Returns current Unix timestamp with microseconds" //ex: 0.45920500 1406776901
* php: {{kbd | key=<nowiki>echo microtime();</nowiki>}}  [http://php.net/manual/en/function.microtime.php PHP: microtime - Manual] "Returns current Unix timestamp with microseconds" //ex: 0.45920500 1406776901
Line 63: Line 65:
  */
  */


 
==== today & yesterday ====
today
today  
* MySQL: {{kbd | key=<nowiki>SELECT  CURRENT_DATE;</nowiki>}} or {{kbd | key=<nowiki>SELECT  CURDATE();</nowiki>}}  Returns {{Template:Today}} <ref>[http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_curdate MySQL :: MySQL 5.5 Reference Manual :: 12.7 Date and Time Functions]</ref>
* MySQL: {{kbd | key=<nowiki>SELECT  CURRENT_DATE;</nowiki>}} or {{kbd | key=<nowiki>SELECT  CURDATE();</nowiki>}}  Returns {{Template:Today}} <ref>[http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_curdate MySQL :: MySQL 5.5 Reference Manual :: 12.7 Date and Time Functions]</ref>
* EXCEL: {{kbd | key=<nowiki>=TODAY()</nowiki>}} Returns {{CURRENTYEAR}}/{{CURRENTMONTH}}/{{CURRENTDAY2}} <ref>[http://office.microsoft.com/en-gb/excel-help/today-function-HP010062297.aspx TODAY function - Excel - Office.com]</ref>
* EXCEL: {{kbd | key=<nowiki>=TODAY()</nowiki>}} Returns {{CURRENTYEAR}}/{{CURRENTMONTH}}/{{CURRENTDAY2}} <ref>[http://office.microsoft.com/en-gb/excel-help/today-function-HP010062297.aspx TODAY function - Excel - Office.com]</ref>

Revision as of 17:34, 9 March 2016

mulitple approaches to completing the same/similar task using PHP, MySQL and Excel

time / timestamp

terms of time format

format \ date 1900/1/1 1970/1/1 2016/1/1
column value of unix timestamp
(the number of seconds since 1970/01/01)
-2209075200 0 1451606400
column value of Excel DATEVALUE function
(number of days since 1900/1/1)
1 25569 42370

now

human readable time format

Convert unix timestamp (the number of seconds since 1970/01/01) <--> to the human readable time format ex: 2026-05-27 02:33:06

  • php: echo date("Y-m-d H:i:s", time() ); //Convert the time stamp of current time to the human readable time format. Ex: return '2026-05-27 02:33:06' Icon_exclaim.gif server timezone dependent
  • mysql: Icon_exclaim.gif server timezone dependent
    • SELECT NOW(); Returns 2026-05-27 02:33:06 which mapping to DATETIME type[1]
    • SELECT NOW()+0; //2011-04-01 12:19:43 returns 20110401122023.000000
    • SELECT CURRENT_TIMESTAMP; Returns 2026-05-27 02:33:06 Icon_exclaim.gif Current time zone of MySQL is SYSTEM timezone dependent.
    • convert mysql timestamp to Taipei datetime [2]
/* detect server timezone automatically */
SELECT convert_tz(
   CURRENT_TIMESTAMP(),   
   CONCAT(
     ROUND(
      TIME_TO_SEC(timediff(now(),convert_tz(now(),@@session.time_zone,'+00:00')))/3600),  ':00')
   , '+08:00');

/* If you already know the server timezone ex: -05:00 */
SELECT convert_tz(CURRENT_TIMESTAMP,  '-05:00', '+08:00');
  • shell script with GUN date installed in Linux Os linux.png , macOS icon_os_mac.png or Cygwin of Win Os windows.png :
    • echo `date +\%Y-\%m-\%d\ %H:%M:%S` 2>&1 or date +\%Y-\%m-\%d\ %H:%M:%S Returns 2026-05-27 02:33:06 Icon_exclaim.gif server timezone dependent
    • echo `TZ=Asia/Taipei date +\%Y-\%m-\%d\ %H:%M:%S` 2>&1 or TZ=Asia/Taipei date +\%Y-\%m-\%d\ %H:%M:%S Returns 2026-05-27 02:33:06 Icon_exclaim.gif force to use Taipei timezone

the current timestamp

ex: 1292897201

  • php: echo time(); //Return the number of seconds since 1970/01/01
  • php: echo microtime(); PHP: microtime - Manual "Returns current Unix timestamp with microseconds" //ex: 0.45920500 1406776901
  • mysql: SELECT UNIX_TIMESTAMP(); //ex: 2011-05-30 01:56:38 returns 1306720622
  • javascript: getTime() Method ex: new Date().getTime(); //Return the number of milliseconds since 1970/01/01 [3]
  • EXCEL: Excel date to Unix timestamp - Stack Overflow

compare the timestamp and human readable time format using MySQL

SELECT UNIX_TIMESTAMP( ) , FROM_UNIXTIME( UNIX_TIMESTAMP( ) ,  '%Y-%m-%d %H:%i:%S' );
/* 
1. timezone of UNIX_TIMESTAMP( ) is UTC
2. second part 'FROM_UNIXTIME( UNIX_TIMESTAMP( ) ,  '%Y-%m-%d %H:%i:%S' )' is server timezone dependent
*/

today & yesterday

today

  • MySQL: SELECT CURRENT_DATE; or SELECT CURDATE(); Returns 2026-05-27 [4]
  • EXCEL: =TODAY() Returns 2026/05/27 [5]
  • shell script in Linux Os linux.png or macOS icon_os_mac.png with GUN date installed: echo `date +\%Y-\%m-\%d` 2>&1 or date +"%Y-%m-%d" Returns 2026-05-27[6]


yesterday

  • MySQL:
  • EXCEL:
  • PHP:
  • shell script in Linux Os linux.png with GUN date installed: echo $(date -d "yesterday" '+%Y-%m-%d')[7] //Returns sample: 2026-05-24

specified time

convert the unix timestamp to human readable time format

ex: 2010-12-21 10:05:06

  • PHP: echo date("Y-m-d H:i:s", 1292897201 ); // Using date() function that converting the time stamp 1292897201 to the human readable time format. similar: gmdate() function [Last visited: 2014-04-30] Icon_exclaim.gif server timezone dependent
  • MySQL:
    • SELECT FROM_UNIXTIME( 1306311155 ); //convert the time stamp 1306311155 to the human readable time format 2011-05-25 08:12:11 Icon_exclaim.gif server timezone dependent
    • SELECT FROM_UNIXTIME( 1306311155, '%Y-%m-%d %H:%i:%S' ); //convert the time stamp 1306311155 to the human readable time format 2011-05-25 08:12:11 Icon_exclaim.gif server timezone dependent
    • convert mysql timestamp to Taipei datetime [8]
/* detect server timezone automatically */
SELECT convert_tz(
   FROM_UNIXTIME( `column_of_timestamp` ,  '%Y-%m-%d %H:%i:%S' ),   
   CONCAT(
     ROUND(
      TIME_TO_SEC(timediff(now(),convert_tz(now(),@@session.time_zone,'+00:00')))/3600),  ':00')
   , '+08:00')
FROM `table`

/* If you already know the server timezone ex: -05:00 */
SELECT convert_tz(
   FROM_UNIXTIME( `column_of_timestamp` ,  '%Y-%m-%d %H:%i:%S' ),  '-05:00', '+08:00')
FROM `table`
  • Excel
    • =( unix_time_stamp /86400)+DATE(1970,1,1) // convert the unix time stamp 1421539200 to the human readable time format 2015/1/18 [9]


convert human-readable time to timestamp

  • PHP: using strtotime() function ex: strtotime('2010-12-21 10:05:06') [10]
  • mysql:
    • SELECT UNIX_TIMESTAMP('2011-03-15 18:53:57'); /* return timestamp: 1300186437 */ Icon_exclaim.gif server timezone dependent
    • SELECT UNIX_TIMESTAMP(STR_TO_DATE('2011-03-15 18:53:57', '%Y-%m-%d %H:%i:%S')); /* return timestamp: 1300186437 */ Icon_exclaim.gif server timezone dependent
  • Excel:
    • input data (A2 cell): YYYY/MM/DD (e.g. 2026/05/27 ) or YYYY/MM/DD HH:MM (e.g. 2026/05/27 02:33)
    • =(A2-DATE(1970,1,1))*86400 [11]

convert datevalue (number of days since 1900/1/1) ↔ to human-readable date

  • Excel: =DATEVALUE(Cell_of_date) // ex: =DATEVALUE("2015/1/27") returns 42031. DATEVALUE of 1900/1/1 is 1
  • Excel: =TEXT(Cell_of_datevalue,"yyyy/mm/dd") // ex: =TEXT(42031,"yyyy/mm/dd") returns 2015/1/27

convert month name to numeric date ex: May 27, 2026 -> 2026-05-27

PHP microtime to MySQL timestamp

PHP microtime to MySQL timestamp

time difference of two time values

  • php: using mktime() function
  • mysql: using TIMEDIFF() function ex: SELECT TIMEDIFF('2016:02:01 00:00:00', '2016:01:01 00:00:00'); /* return 744:00:00 */

date interval

When people said 2026-05-01 ~ 2026-05-03, it means 2026-05-01 00:00:00 ~ 2026-05-03 59:59:59 in the system.

Query by month

mysql ex: find the records in January, 2026[13] Data type of column `time` is datetime (ex: yy:mm:dd hh:mm:ss). Using one of sql queries as following. online demo

  • SELECT * FROM `table_name` WHERE YEAR(`time`) = '2026' AND MONTH(`time`) = '1' /*MONTH(`time`) = '1' or MONTH(`time`) = '01' are both ok*/
  • SELECT * FROM `table_name` WHERE DATE_FORMAT(`time`, '%Y-%m') = '2026-01'
  • SELECT * FROM `table_name` WHERE `time` LIKE '2026-01%' /*find the time records starting with the string 2026-01 */
  • SELECT * FROM `table_name` WHERE DATE(`time`) between '2026-01-01' AND '2026-01-31' Icon_exclaim.gif add the DATE function to the `time` field
  • SELECT * FROM `table_name` WHERE `time` >= '2026-01-01 00:00:00' AND `time` < '2026-02-01 00:00:00'
  • SELECT * FROM `table_name` WHERE `time` >= '2026-01-01 00:00:00' AND `time` <= '2026-01-31 59:59:59'

date format

sample output: 2026-05-27


further reading

Math

Format a number

Round a number downward to its nearest integer

other

  • a >0 OR b > 0 OR c > 0
  • a+b+c > 0

trigger to make backup of deleted data before deleting them

MySQL :: Re: before delete trigger to make backup of deleted data

step 1: create table hello_deleted_data with the same structure of table hello

step 2: add a trigger

create trigger hello before delete on hello 
for each row 
insert into hello_deleted_data (x,y,z) 
values (OLD.x, OLD.y, OLD.z); 

tested on version: mysqlnd 5.0.7-dev - 091210

redirect/reload to (another) page

redirect


reload

  • Javascript
    • iframe (reload) - parent.location.reload();

find unique (non duplicated) data

  • SELECT DISTINCT column FROM table[14]
  • (1)SELECT * FROM table; (2)Using PHP: array_unique for data handling two or more columns
  • SELECT column FROM table GROUP BY column

text match

//PHP code snippet:
$array = array("AAA", "BBB", "CCC");

if(in_array($var, $array){
//do something
}
  • preg_match...
  • verbose approach: Icon_exclaim.gif IF (0 == 'String') always be true?[15]
if($var =="AAA" OR $var =="BBB" OR $var =="CCC"){
//do something
}

text input filter

export/import sql file

export/import sql file


reverse the boolean value

  • PHP:
$var = true;
print( !$var); //add ! symbol to reverse the boolean value

ideas

filter some records

  • approach 1: (1) select * under some condition, (2) collect the $identifiers which matched the condition. and then (3) select some records NOT IN ( $identifiers )
  • approach 2: (1) select * and then (2) unset some records which matched the condition.

documentation

How to generate the table schema

  1. Using phpMyAdmin or other MySQL client
  2. Input the SQL query:
    EXPLAIN table_name;
  3. Print view (with full texts)
  4. Easy to copy the table to other work processor
  5. (optional) Adjust the text size to 10

debug

SQL syntax debug

references