$diff = (number_format((time() - strtotime($date_to_check)) / (60 * 60 * 24), 2));
if ($diff > 0)
{
echo "$date is $diff days ago from today";
}
Tuesday, December 22, 2009
Monday, December 21, 2009
Ajax with JSON returned from response (Prototype)
Javascript code:
----------------
edit_info = function(id) {
url = 'www.test.com/get_info?id=' + id;
new Ajax.Request(url, {
method: 'post',
onComplete: function(req) {
var data = eval("("+req.responseText+")");
$('email').value = data['email'];
$('city').value = data['city'];
}
});
}
PHP code:
---------
public function get_info() {
$info = db.query('select * from info where id='.$_REQUEST['id']);
echo json_encode($info);
exit;
}
----------------
edit_info = function(id) {
url = 'www.test.com/get_info?id=' + id;
new Ajax.Request(url, {
method: 'post',
onComplete: function(req) {
var data = eval("("+req.responseText+")");
$('email').value = data['email'];
$('city').value = data['city'];
}
});
}
PHP code:
---------
public function get_info() {
$info = db.query('select * from info where id='.$_REQUEST['id']);
echo json_encode($info);
exit;
}
Thursday, December 17, 2009
CONCAT value in GROUP BY in mysql
You can actually concat-ing values returned by group by query by doing this:
SELECT GROUP_CONCAT(DISTINCT name ORDER BY name SEPARATOR ',')
FROM animals
WHERE type IN ('bird',''reptile)
GROUP BY type
SELECT GROUP_CONCAT(DISTINCT name ORDER BY name SEPARATOR ',')
FROM animals
WHERE type IN ('bird',''reptile)
GROUP BY type
Tuesday, December 15, 2009
First date and last date of month PHP
// for current month
$start_date = date("Y-m-d", strtotime(date('Y-m').'-01 00:00:00'));
$end_date = date("Y-m-d", strtotime('-1 second',strtotime('+1 month',strtotime(date('Y-m').'-01 00:00:00'))));
// for specific month
$start_date = date("Y-m-d", strtotime(date('Y').'-'.$month.'-01 00:00:00'));
$end_date = date("Y-m-d", strtotime('-1 second',strtotime('+1 month',strtotime(date('Y').'-'.$month.'-01 00:00:00'))));
$start_date = date("Y-m-d", strtotime(date('Y-m').'-01 00:00:00'));
$end_date = date("Y-m-d", strtotime('-1 second',strtotime('+1 month',strtotime(date('Y-m').'-01 00:00:00'))));
// for specific month
$start_date = date("Y-m-d", strtotime(date('Y').'-'.$month.'-01 00:00:00'));
$end_date = date("Y-m-d", strtotime('-1 second',strtotime('+1 month',strtotime(date('Y').'-'.$month.'-01 00:00:00'))));
Google Chart / Graph PHP Class Helper (by me)
//Here is a little helper:
//========================
class GoogleGraphHelper {
public $api_url = "";
public $request = array();
public $maxValue = 0;
public $colorSet = array('FF0000', '00FF00', '0000FF', '000000', 'FFFF00', '00FFFF');
public $markerSet = array('o','s','x','c','d','c','x','s','o');
private $datapointLimit = 100;
private $dapointSetLimit = 4;
public function __construct() {
$this->api_url = "http://chart.apis.google.com/chart?";
$this->request = array(
'chart_type' => "cht=lc",
'chart_size' => "chs=600x500",
'chart_data' => "",
'chart_colors' => "",
'chart_legends' => "",
'chart_labels' => "",
'chart_markers' => "",
);
}
public function get_graph($data, $xlabels = array(), $ylabels = array()) {
self::set_data($data);
self::set_colors($data);
self::set_legends($data);
self::set_labels($xlabels, $ylabels);
self::set_markers($data);
return $this->api_url.implode("&", $this->request);
}
public function encode($data, $maxValue) {
$simpleEncoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$chartData = "";
$len = sizeof($data);
for ($i = 0; $i < $len; $i++) {
$currentValue = $data[$i];
if (is_numeric($currentValue) && $currentValue >= 0) {
$chartData .= substr($simpleEncoding, round((strlen($simpleEncoding)-1) * $currentValue / $maxValue), 1);
}
else {
$chartData .= '_';
}
}
return $chartData;
}
public function set_data($data = array()) {
self::find_max($data);
$encoded_data = array();
foreach ($data as $key => $info) {
$encoded_data[] = self::encode($info['values'], $this->maxValue);
}
$this->request['chart_data'] = "chd=s:".implode(",", $encoded_data);
}
public function set_size($width, $height) {
$this->request['chart_size'] = "chs={$width}x{$height}";
}
public function set_type($type) {
$this->request['chart_type'] = "cht={$type}";
}
public function set_colors(&$data) {
$this->request['chart_colors'] = "chco=";
$colors = array();
foreach($data as &$d) {
if (!isset($d['color']))
$d['color'] = array_pop($this->colorSet);
$colors[] = $d['color'];
}
$this->request['chart_colors'] .= implode(",", $colors);
}
public function set_legends($data) {
$labels = array_keys($data);
$this->request['chart_legends'] = "chdl=". implode("|",$labels);
}
public function set_labels($xlabels, $ylabels) {
$this->request['chart_labels'] = "chxt=y,x";
if (!empty($xlabels))
$this->request['chart_labels'] .= "&chxl=1:|".implode("|",$xlabels);
if (empty($ylabels))
$this->request['chart_labels'] .= "&chxr=0,0,{$this->maxValue}";
else
$this->request['chart_labels'] .= "&chxr=0,".implode(",", $ylablels);
}
public function set_markers(&$data) {
$this->request['chart_markers'] = 'chm=';
$markers = array();
$i = 0;
foreach($data as &$d) {
if (!isset($d['marker']))
$d['marker'] = array_pop($this->markerSet);
$markers[] = $d['marker'].",".$d['color'].",".$i.","."-1,10";
$i++;
}
$this->request['chart_markers'] .= implode("|", $markers);
}
public function find_max($data) {
foreach ($data as $d) {
$max = round(max($d['values']) * 1.10);
$this->maxValue = ($this->maxValue < $max)? $max: $this->maxValue;
}
}
}
//How to use:
//=============================
$data = array(
'uno' => array(
'values' => array(40,60,60,45,47,75,70,72),
),
'dos' => array(
'values' => array(50,70,70,55,57,85,80,82),
),
);
$gg = new GoogleGraphHelper();
$gg->set_size(300,200);
$url = $gg->get_graph($data, array("jan", "feb", "march"));
echo $url;
// it will return
// ==============================
http://chart.apis.google.com/chart?cht=lc&chs=300x200&chd=s:anndfxtv,gttkl301&chco=00FFFF,FFFF00&chdl=uno|dos&chxt=y,x&chxl=1:|jan|feb|march&chxr=0,0,94&chm=o,00FFFF,0,-1,10|s,FFFF00,1,-1,10
//========================
class GoogleGraphHelper {
public $api_url = "";
public $request = array();
public $maxValue = 0;
public $colorSet = array('FF0000', '00FF00', '0000FF', '000000', 'FFFF00', '00FFFF');
public $markerSet = array('o','s','x','c','d','c','x','s','o');
private $datapointLimit = 100;
private $dapointSetLimit = 4;
public function __construct() {
$this->api_url = "http://chart.apis.google.com/chart?";
$this->request = array(
'chart_type' => "cht=lc",
'chart_size' => "chs=600x500",
'chart_data' => "",
'chart_colors' => "",
'chart_legends' => "",
'chart_labels' => "",
'chart_markers' => "",
);
}
public function get_graph($data, $xlabels = array(), $ylabels = array()) {
self::set_data($data);
self::set_colors($data);
self::set_legends($data);
self::set_labels($xlabels, $ylabels);
self::set_markers($data);
return $this->api_url.implode("&", $this->request);
}
public function encode($data, $maxValue) {
$simpleEncoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$chartData = "";
$len = sizeof($data);
for ($i = 0; $i < $len; $i++) {
$currentValue = $data[$i];
if (is_numeric($currentValue) && $currentValue >= 0) {
$chartData .= substr($simpleEncoding, round((strlen($simpleEncoding)-1) * $currentValue / $maxValue), 1);
}
else {
$chartData .= '_';
}
}
return $chartData;
}
public function set_data($data = array()) {
self::find_max($data);
$encoded_data = array();
foreach ($data as $key => $info) {
$encoded_data[] = self::encode($info['values'], $this->maxValue);
}
$this->request['chart_data'] = "chd=s:".implode(",", $encoded_data);
}
public function set_size($width, $height) {
$this->request['chart_size'] = "chs={$width}x{$height}";
}
public function set_type($type) {
$this->request['chart_type'] = "cht={$type}";
}
public function set_colors(&$data) {
$this->request['chart_colors'] = "chco=";
$colors = array();
foreach($data as &$d) {
if (!isset($d['color']))
$d['color'] = array_pop($this->colorSet);
$colors[] = $d['color'];
}
$this->request['chart_colors'] .= implode(",", $colors);
}
public function set_legends($data) {
$labels = array_keys($data);
$this->request['chart_legends'] = "chdl=". implode("|",$labels);
}
public function set_labels($xlabels, $ylabels) {
$this->request['chart_labels'] = "chxt=y,x";
if (!empty($xlabels))
$this->request['chart_labels'] .= "&chxl=1:|".implode("|",$xlabels);
if (empty($ylabels))
$this->request['chart_labels'] .= "&chxr=0,0,{$this->maxValue}";
else
$this->request['chart_labels'] .= "&chxr=0,".implode(",", $ylablels);
}
public function set_markers(&$data) {
$this->request['chart_markers'] = 'chm=';
$markers = array();
$i = 0;
foreach($data as &$d) {
if (!isset($d['marker']))
$d['marker'] = array_pop($this->markerSet);
$markers[] = $d['marker'].",".$d['color'].",".$i.","."-1,10";
$i++;
}
$this->request['chart_markers'] .= implode("|", $markers);
}
public function find_max($data) {
foreach ($data as $d) {
$max = round(max($d['values']) * 1.10);
$this->maxValue = ($this->maxValue < $max)? $max: $this->maxValue;
}
}
}
//How to use:
//=============================
$data = array(
'uno' => array(
'values' => array(40,60,60,45,47,75,70,72),
),
'dos' => array(
'values' => array(50,70,70,55,57,85,80,82),
),
);
$gg = new GoogleGraphHelper();
$gg->set_size(300,200);
$url = $gg->get_graph($data, array("jan", "feb", "march"));
echo $url;
// it will return
// ==============================
http://chart.apis.google.com/chart?cht=lc&chs=300x200&chd=s:anndfxtv,gttkl301&chco=00FFFF,FFFF00&chdl=uno|dos&chxt=y,x&chxl=1:|jan|feb|march&chxr=0,0,94&chm=o,00FFFF,0,-1,10|s,FFFF00,1,-1,10
Wednesday, December 9, 2009
Date iteration PHP
$today = date('Y-m-d');
$date_start = $today
$date_end = date('Y-m-d', strtotime("{$date_start} + 30 days"));
while ($date_start != $date_end) {
echo "\n$date_start";
date_start = date('Y-m-d', strtotime("{date_start} + 1 day"));
}
===================
OUTPUT:
2009-12-01
2009-12-02
2009-12-03
.
.
.
and so on...
$date_start = $today
$date_end = date('Y-m-d', strtotime("{$date_start} + 30 days"));
while ($date_start != $date_end) {
echo "\n$date_start";
date_start = date('Y-m-d', strtotime("{date_start} + 1 day"));
}
===================
OUTPUT:
2009-12-01
2009-12-02
2009-12-03
.
.
.
and so on...
Monday, November 23, 2009
require, require_once, include, include_once
Difference between require() and require_once(): require() includes and evaluates a specific file while require_once() does that only if it has not been included before (on the same page).
So require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the function re-declared error.
Difference between require() and include() is that require() produces a FATAL ERROR if the file you want to include is not found while include() only produces a WARNING.
There is also include_once() which is the same as include() but the difference between them is the same as the difference between require() and require_once().
So require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the function re-declared error.
Difference between require() and include() is that require() produces a FATAL ERROR if the file you want to include is not found while include() only produces a WARNING.
There is also include_once() which is the same as include() but the difference between them is the same as the difference between require() and require_once().
Monday, October 26, 2009
Regex pattern modifier -PHP/Perl
i
When this modifier is used, the matching of alphabetic characters in the pattern becomes non-case-sensitive; for example, "/sgi/i" matches both "sgi" and "SGI." This is equivalent to Perl's /i modifier.
m
By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless the D modifier is also set). This is the same as in Perl.
When this modifier is used, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.
s
When this modifier is used, a dot metacharacter (.) in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.
x
When this modifier is used, whitespace data characters in the pattern are ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters cannot appear within special character sequences in a pattern, for example within the sequence (?(, which introduces a conditional subpattern.
e
When this modifier is used, preg_replace() does normal substitution of references in the replacement string, evaluates it as PHP code, and uses the result of the evaluation for replacing the match found by the pattern.
Only preg_replace() uses this modifier; it's ignored by other PCRE functions.
A
When this modifier is used, the pattern is forced to be "anchored"; that is, it's constrained to match only at the start of the string that's being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.
D
When this modifier is used, a dollar metacharacter ($) in the pattern matches only at the end of the subject string. Without this modifier, a dollar sign also matches immediately before the final character if it's a newline (but not before any other newlines). This modifier is ignored if the /m modifier is set. There is no equivalent to this modifier in Perl.
S
When a pattern is going to be used several times, it's worth spending more time analyzing it in order to speed up the time taken for matching. When this modifier is used, this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that don't have a single fixed starting character. This is equivalent to the study() function in Perl.
U
This modifier inverts the "greediness" of the quantifiers so that they're not greedy by default, but become greedy if followed by "?". Greedy quantifiers attempt to match as much of the target string as they legally can. The only limit on this behavior is that the greediness of one quantifier cannot cause the following other quantifiers in the pattern to fail. This modifier is not compatible with Perl.
X
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Any backslash in a pattern that's followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. At present, no other features are controlled by this modifier.
When this modifier is used, the matching of alphabetic characters in the pattern becomes non-case-sensitive; for example, "/sgi/i" matches both "sgi" and "SGI." This is equivalent to Perl's /i modifier.
m
By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless the D modifier is also set). This is the same as in Perl.
When this modifier is used, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.
s
When this modifier is used, a dot metacharacter (.) in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.
x
When this modifier is used, whitespace data characters in the pattern are ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters cannot appear within special character sequences in a pattern, for example within the sequence (?(, which introduces a conditional subpattern.
e
When this modifier is used, preg_replace() does normal substitution of references in the replacement string, evaluates it as PHP code, and uses the result of the evaluation for replacing the match found by the pattern.
Only preg_replace() uses this modifier; it's ignored by other PCRE functions.
A
When this modifier is used, the pattern is forced to be "anchored"; that is, it's constrained to match only at the start of the string that's being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.
D
When this modifier is used, a dollar metacharacter ($) in the pattern matches only at the end of the subject string. Without this modifier, a dollar sign also matches immediately before the final character if it's a newline (but not before any other newlines). This modifier is ignored if the /m modifier is set. There is no equivalent to this modifier in Perl.
S
When a pattern is going to be used several times, it's worth spending more time analyzing it in order to speed up the time taken for matching. When this modifier is used, this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that don't have a single fixed starting character. This is equivalent to the study() function in Perl.
U
This modifier inverts the "greediness" of the quantifiers so that they're not greedy by default, but become greedy if followed by "?". Greedy quantifiers attempt to match as much of the target string as they legally can. The only limit on this behavior is that the greediness of one quantifier cannot cause the following other quantifiers in the pattern to fail. This modifier is not compatible with Perl.
X
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Any backslash in a pattern that's followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. At present, no other features are controlled by this modifier.
Regex pattern modifier -PHP/Perl
i
When this modifier is used, the matching of alphabetic characters in the pattern becomes non-case-sensitive; for example, "/sgi/i" matches both "sgi" and "SGI." This is equivalent to Perl's /i modifier.
m
By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless the D modifier is also set). This is the same as in Perl.
When this modifier is used, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.
s
When this modifier is used, a dot metacharacter (.) in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.
x
When this modifier is used, whitespace data characters in the pattern are ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters cannot appear within special character sequences in a pattern, for example within the sequence (?(, which introduces a conditional subpattern.
e
When this modifier is used, preg_replace() does normal substitution of references in the replacement string, evaluates it as PHP code, and uses the result of the evaluation for replacing the match found by the pattern.
Only preg_replace() uses this modifier; it's ignored by other PCRE functions.
A
When this modifier is used, the pattern is forced to be "anchored"; that is, it's constrained to match only at the start of the string that's being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.
D
When this modifier is used, a dollar metacharacter ($) in the pattern matches only at the end of the subject string. Without this modifier, a dollar sign also matches immediately before the final character if it's a newline (but not before any other newlines). This modifier is ignored if the /m modifier is set. There is no equivalent to this modifier in Perl.
S
When a pattern is going to be used several times, it's worth spending more time analyzing it in order to speed up the time taken for matching. When this modifier is used, this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that don't have a single fixed starting character. This is equivalent to the study() function in Perl.
U
This modifier inverts the "greediness" of the quantifiers so that they're not greedy by default, but become greedy if followed by "?". Greedy quantifiers attempt to match as much of the target string as they legally can. The only limit on this behavior is that the greediness of one quantifier cannot cause the following other quantifiers in the pattern to fail. This modifier is not compatible with Perl.
X
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Any backslash in a pattern that's followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. At present, no other features are controlled by this modifier.
When this modifier is used, the matching of alphabetic characters in the pattern becomes non-case-sensitive; for example, "/sgi/i" matches both "sgi" and "SGI." This is equivalent to Perl's /i modifier.
m
By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless the D modifier is also set). This is the same as in Perl.
When this modifier is used, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.
s
When this modifier is used, a dot metacharacter (.) in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.
x
When this modifier is used, whitespace data characters in the pattern are ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters cannot appear within special character sequences in a pattern, for example within the sequence (?(, which introduces a conditional subpattern.
e
When this modifier is used, preg_replace() does normal substitution of references in the replacement string, evaluates it as PHP code, and uses the result of the evaluation for replacing the match found by the pattern.
Only preg_replace() uses this modifier; it's ignored by other PCRE functions.
A
When this modifier is used, the pattern is forced to be "anchored"; that is, it's constrained to match only at the start of the string that's being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.
D
When this modifier is used, a dollar metacharacter ($) in the pattern matches only at the end of the subject string. Without this modifier, a dollar sign also matches immediately before the final character if it's a newline (but not before any other newlines). This modifier is ignored if the /m modifier is set. There is no equivalent to this modifier in Perl.
S
When a pattern is going to be used several times, it's worth spending more time analyzing it in order to speed up the time taken for matching. When this modifier is used, this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that don't have a single fixed starting character. This is equivalent to the study() function in Perl.
U
This modifier inverts the "greediness" of the quantifiers so that they're not greedy by default, but become greedy if followed by "?". Greedy quantifiers attempt to match as much of the target string as they legally can. The only limit on this behavior is that the greediness of one quantifier cannot cause the following other quantifiers in the pattern to fail. This modifier is not compatible with Perl.
X
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Any backslash in a pattern that's followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. At present, no other features are controlled by this modifier.
Thursday, October 15, 2009
Email validation function
function validEmail($email) {
$email = trim($email);
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if (strpos($domain, ".") === false) {
//domain does not have a period
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
//remove, just check formatting for now
/*if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
*/
}
return $isValid;
}
$email = trim($email);
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if (strpos($domain, ".") === false) {
//domain does not have a period
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
//remove, just check formatting for now
/*if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
*/
}
return $isValid;
}
Create State Drop Down Menu
function makeStateDropDown($state='') {
$state = trim($state);
$dropdown = "";
$states = array(
"Alabama" => "AL",
"Alaska" => "AK",
"Arizona" => "AZ",
"Arkansas" => "AR",
"California" => "CA",
"Colorado" => "CO",
"Connecticut" => "CT",
"Delaware" => "DE",
"Florida" => "FL",
"Georgia" => "GA",
"Hawaii" => "HI",
"Idaho" => "ID",
"Illinois" => "IL",
"Indiana" => "IN",
"Iowa" => "IA",
"Kansas" => "KS",
"Kentucky" => "KY",
"Louisiana" => "LA",
"Maine" => "ME",
"Maryland" => "MD",
"Massachusetts" => "MA",
"Michigan" => "MI",
"Minnesota" => "MN",
"Mississippi" => "MS",
"Missouri" => "MO",
"Montana" => "MT",
"Nebraska" => "NE",
"Nevada" => "NV",
"New Hampshire" => "NH",
"New Jersey" => "NJ",
"New Mexico" => "NM",
"New York" => "NY",
"North Carolina" => "NC",
"North Dakota" => "ND",
"Ohio" => "OH",
"Oklahoma" => "OK",
"Oregon" => "OR",
"Pennsylvania" => "PA",
"Rhode Island" => "RI",
"South Carolina" => "SC",
"South Dakota" => "SD",
"Tennessee" => "TN",
"Texas" => "TX",
"Utah" => "UT",
"Vermont" => "VT",
"Virginia" => "VA",
"Washington" => "WA",
"Washington DC" => "DC",
"West Virginia" => "WV",
"Wisconsin" => "WI",
"Wyoming" => "WY"
);
foreach($states as $key=>$val) {
$selected = "";
if(strtolower($key) == strtolower($state) || strtolower($val) == strtolower($state)) {
$selected = " selected";
}
$dropdown = "$dropdown \n";
}
return $dropdown;
}
$state = trim($state);
$dropdown = "";
$states = array(
"Alabama" => "AL",
"Alaska" => "AK",
"Arizona" => "AZ",
"Arkansas" => "AR",
"California" => "CA",
"Colorado" => "CO",
"Connecticut" => "CT",
"Delaware" => "DE",
"Florida" => "FL",
"Georgia" => "GA",
"Hawaii" => "HI",
"Idaho" => "ID",
"Illinois" => "IL",
"Indiana" => "IN",
"Iowa" => "IA",
"Kansas" => "KS",
"Kentucky" => "KY",
"Louisiana" => "LA",
"Maine" => "ME",
"Maryland" => "MD",
"Massachusetts" => "MA",
"Michigan" => "MI",
"Minnesota" => "MN",
"Mississippi" => "MS",
"Missouri" => "MO",
"Montana" => "MT",
"Nebraska" => "NE",
"Nevada" => "NV",
"New Hampshire" => "NH",
"New Jersey" => "NJ",
"New Mexico" => "NM",
"New York" => "NY",
"North Carolina" => "NC",
"North Dakota" => "ND",
"Ohio" => "OH",
"Oklahoma" => "OK",
"Oregon" => "OR",
"Pennsylvania" => "PA",
"Rhode Island" => "RI",
"South Carolina" => "SC",
"South Dakota" => "SD",
"Tennessee" => "TN",
"Texas" => "TX",
"Utah" => "UT",
"Vermont" => "VT",
"Virginia" => "VA",
"Washington" => "WA",
"Washington DC" => "DC",
"West Virginia" => "WV",
"Wisconsin" => "WI",
"Wyoming" => "WY"
);
foreach($states as $key=>$val) {
$selected = "";
if(strtolower($key) == strtolower($state) || strtolower($val) == strtolower($state)) {
$selected = " selected";
}
$dropdown = "$dropdown \n";
}
return $dropdown;
}
Number to Roman
function numberToRoman($num)
{
// Make sure that we only use the integer portion of the value
$n = intval($num);
$result = '';
// Declare a lookup array that we will use to traverse the number:
$lookup = array('M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400,
'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
foreach ($lookup as $roman => $value)
{
// Determine the number of matches
$matches = intval($n / $value);
// Store that many characters
$result .= str_repeat($roman, $matches);
// Substract that from the number
$n = $n % $value;
}
// The Roman numeral should be built, return it
return $result;
}
{
// Make sure that we only use the integer portion of the value
$n = intval($num);
$result = '';
// Declare a lookup array that we will use to traverse the number:
$lookup = array('M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400,
'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
foreach ($lookup as $roman => $value)
{
// Determine the number of matches
$matches = intval($n / $value);
// Store that many characters
$result .= str_repeat($roman, $matches);
// Substract that from the number
$n = $n % $value;
}
// The Roman numeral should be built, return it
return $result;
}
Roman to number function
function romanToNumber($input)
{
$intvalues = array();
$intLoopI = 0;
$intTotal = 0;
$intPreviousPointer = 99999;
$intCurrentPointer = 0;
$intvalues['M'] = 1000;
$intvalues['D'] = 500;
$intvalues['C'] = 100;
$intvalues['L'] = 50;
$intvalues['X'] = 10;
$intvalues['V'] = 5;
$intvalues['I'] = 1;
for ($intLoopI = 0; $intLoopI < strlen($input) - 1; $intLoopI++)
{
$intCurrentPointer = $intvalues[substr($input, $intLoopI, 1)];
$intTotal += $intCurrentPointer;
if ($intCurrentPointer > $intPreviousPointer)
$intTotal -= (2 * $intPreviousPointer);
$intPreviousPointer = $intCurrentPointer;
}
return $intTotal;
}
{
$intvalues = array();
$intLoopI = 0;
$intTotal = 0;
$intPreviousPointer = 99999;
$intCurrentPointer = 0;
$intvalues['M'] = 1000;
$intvalues['D'] = 500;
$intvalues['C'] = 100;
$intvalues['L'] = 50;
$intvalues['X'] = 10;
$intvalues['V'] = 5;
$intvalues['I'] = 1;
for ($intLoopI = 0; $intLoopI < strlen($input) - 1; $intLoopI++)
{
$intCurrentPointer = $intvalues[substr($input, $intLoopI, 1)];
$intTotal += $intCurrentPointer;
if ($intCurrentPointer > $intPreviousPointer)
$intTotal -= (2 * $intPreviousPointer);
$intPreviousPointer = $intCurrentPointer;
}
return $intTotal;
}
implode on field
function implode_on_field($delimiter, Array $objects, $field)
{
$d = array();
foreach ($objects as $ob)
$d[] = $ob->{$field};
return implode($delimiter, $d);
}
======================================
example:
$obj = array();
for ($i = 0; $i < 5; $i++) {
$obj[] = array('id' => $i, 'type' => 'x');
}
$out = implode_on_field(',', $obj, 'id');
echo $out;
=======================================
output:
1,2,3,4,5
{
$d = array();
foreach ($objects as $ob)
$d[] = $ob->{$field};
return implode($delimiter, $d);
}
======================================
example:
$obj = array();
for ($i = 0; $i < 5; $i++) {
$obj[] = array('id' => $i, 'type' => 'x');
}
$out = implode_on_field(',', $obj, 'id');
echo $out;
=======================================
output:
1,2,3,4,5
Wednesday, October 14, 2009
Date query tips
Use 'between' when searching for rows based on dates instead of using 'like'.
Reason: 'like' doesnt search using indexes so it might slow down your query.
$today = date('Y-m-d');
$firstDayMonth = date("Y-m-d", mktime(0, 0, 0, date("m") , date("d")-date("d")+1, date("Y")));
examples:
-bad
(SELECT SUM(amount) from merchant_lead_order_charges WHERE merchant_lead_order_charges.date is between '" . date('Y-m') . "%')
-good
(SELECT SUM(amount) from merchant_lead_order_charges WHERE merchant_lead_order_charges.date between '" . $firstDayMonth . "' and '".$today."')
Reason: 'like' doesnt search using indexes so it might slow down your query.
$today = date('Y-m-d');
$firstDayMonth = date("Y-m-d", mktime(0, 0, 0, date("m") , date("d")-date("d")+1, date("Y")));
examples:
-bad
(SELECT SUM(amount) from merchant_lead_order_charges WHERE merchant_lead_order_charges.date is between '" . date('Y-m') . "%')
-good
(SELECT SUM(amount) from merchant_lead_order_charges WHERE merchant_lead_order_charges.date between '" . $firstDayMonth . "' and '".$today."')
Thursday, September 24, 2009
Building subversion on MAC OS X
make bash_login
=======================
mate ~/.bash_login
put this line in
================
export PATH="/usr/local/bin:/usr/local/sbin:$PATH"
-> save it and exit
run it
==========
. ~/.bash_login
get the source and install
============================
curl -O http://subversion.tigris.org/downloads/subversion-1.4.3.tar.gz
curl -O http://subversion.tigris.org/downloads/subversion-deps-1.4.3.tar.gz
tar xzvf subversion-1.4.3.tar.gz
tar xzvf subversion-deps-1.4.3.tar.gz
cd subversion-1.4.3
./configure --prefix=/usr/local --with-openssl --with-ssl --with-zlib=/usr
make
sudo make install
cd ..
=======================
mate ~/.bash_login
put this line in
================
export PATH="/usr/local/bin:/usr/local/sbin:$PATH"
-> save it and exit
run it
==========
. ~/.bash_login
get the source and install
============================
curl -O http://subversion.tigris.org/downloads/subversion-1.4.3.tar.gz
curl -O http://subversion.tigris.org/downloads/subversion-deps-1.4.3.tar.gz
tar xzvf subversion-1.4.3.tar.gz
tar xzvf subversion-deps-1.4.3.tar.gz
cd subversion-1.4.3
./configure --prefix=/usr/local --with-openssl --with-ssl --with-zlib=/usr
make
sudo make install
cd ..
Wednesday, September 23, 2009
Arrayaccess
class obj implements arrayaccess {
private $container = array();
public function __construct() {
$this->container = array(
"one" => 1,
"two" => 2,
"three" => 3,
);
}
public function offsetSet($offset, $value) {
$this->container[$offset] = $value;
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
$obj = new obj;
var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
?>
Out:
bool(true)
int(2)
bool(false)
string(7) "A value"
private $container = array();
public function __construct() {
$this->container = array(
"one" => 1,
"two" => 2,
"three" => 3,
);
}
public function offsetSet($offset, $value) {
$this->container[$offset] = $value;
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
$obj = new obj;
var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
?>
Out:
bool(true)
int(2)
bool(false)
string(7) "A value"
Tuesday, August 25, 2009
Thursday, August 20, 2009
File upload PHP
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000">
Choose a file to upload: <input name="uploadedfile" type="file"><br />
<input type="submit" value="Upload File">
</form>
</pre>
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Wednesday, August 12, 2009
New line to < br >
nl2br — Inserts HTML line breaks before all newlines in a string
$string = "line1\n line2";
$string = nl2br($string);
output:
$string = "line1 <.br.>
line2";
Tuesday, August 11, 2009
creating directory in PHP
$target = "./files/";
$dir = "somedir";
if ( !is_dir($target.$dir) ) {
if( mkdir($target.$dir,0777,true) ) {
echo "success!";
}
}
$dir = "somedir";
if ( !is_dir($target.$dir) ) {
if( mkdir($target.$dir,0777,true) ) {
echo "success!";
}
}
Thursday, July 30, 2009
AJAX request
var xmlhttp;
function showSpecial()
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ('Browser does not support HTTP Request');
return;
}
var url='ajax.php';
url=url+'?special=1';
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open('GET',url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById('special').innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject('Microsoft.XMLHTTP');
}
return null;
}
in ur ajax.php
echo "test";
it will print out "test" inside the:
function showSpecial()
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ('Browser does not support HTTP Request');
return;
}
var url='ajax.php';
url=url+'?special=1';
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open('GET',url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById('special').innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject('Microsoft.XMLHTTP');
}
return null;
}
in ur ajax.php
echo "test";
it will print out "test" inside the:
test
Wednesday, July 29, 2009
My own PHP query builder
say you have this array of column name and its value:
$arr = array('str' => 9, 'agi' => 10, 'name' => 'foo')
use this query builder to create your insert or update query:
function query_builder($arr, $table_name, $type, $clause="") {
if ($type == "insert") {
$q = "$type into $table_name";
$keys = "";
$values = "";
foreach ($arr as $key => $value) {
$keys .= "`$key`, ";
$values .= "?, ";
}
$keys = substr_replace($keys,"",-2);
$values = substr_replace($values,"",-2);
$q .= "($keys) values($values)";
}
else if ($type == "update") {
$q = "$type $table_name set ";
foreach ($arr as $key => $value) {
$q .= "`$key` = ?, ";
}
$q = substr_replace($q,"",-2);
$q .= " where $clause";
}
return $q;
}
example:
$q = query_builder($arr,"table_1","insert");
or
$q = query_builder($arr,"table_1","update","id = 123");
$values = array_values($arr);
//fyi, my DB uses PDOStatement->execute
$db = new DB();
$db->run($q, $values);
$arr = array('str' => 9, 'agi' => 10, 'name' => 'foo')
use this query builder to create your insert or update query:
function query_builder($arr, $table_name, $type, $clause="") {
if ($type == "insert") {
$q = "$type into $table_name";
$keys = "";
$values = "";
foreach ($arr as $key => $value) {
$keys .= "`$key`, ";
$values .= "?, ";
}
$keys = substr_replace($keys,"",-2);
$values = substr_replace($values,"",-2);
$q .= "($keys) values($values)";
}
else if ($type == "update") {
$q = "$type $table_name set ";
foreach ($arr as $key => $value) {
$q .= "`$key` = ?, ";
}
$q = substr_replace($q,"",-2);
$q .= " where $clause";
}
return $q;
}
example:
$q = query_builder($arr,"table_1","insert");
or
$q = query_builder($arr,"table_1","update","id = 123");
$values = array_values($arr);
//fyi, my DB uses PDOStatement->execute
$db = new DB();
$db->run($q, $values);
Tuesday, July 28, 2009
Get all filenames in a directory PHP
$string="";
$fileCount=0;
$filePath=$PATH.'/var/www/public_html/'; # Specify the path you want to look in.
$dir = opendir($filePath); # Open the path
while ($file = readdir($dir)) {
if (eregi("\.php",$file)) { # Look at only files with a .php extension
$string .= "$file
";
$fileCount++;
}
}
if ($fileCount > 0) {
echo sprintf("List of Files in %s
%sTotal Files: %s",$filePath,$string,$fileCount);
}
Friday, July 24, 2009
FBJS: adding id and onclick attribute
// create new div element
var d = document.getElementById('some_element');
var newdiv = document.createElement('div');
newdiv.setId('newid');
var content = ''an anchor html tag with id='test'"; // can't really put html code in blogger for some reason lol
newdiv.setInnerXHTML(content);
d.appendChild(newdiv);
// add an onclick attribute inside id 'test'
document.getElementById('test').addEventListener('click', function() {foo();} );
=================
var d = document.getElementById('some_element');
var newdiv = document.createElement('div');
newdiv.setId('newid');
var content = ''an anchor html tag with id='test'"; // can't really put html code in blogger for some reason lol
newdiv.setInnerXHTML(content);
d.appendChild(newdiv);
// add an onclick attribute inside id 'test'
document.getElementById('test').addEventListener('click', function() {foo();} );
=================
Wednesday, July 15, 2009
SQL Join
- JOIN: Return rows when there is at least one match in both tables
- LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
- RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
- FULL JOIN: Return rows when there is a match in one of the tables
Monday, July 13, 2009
Removing last char
PHP:
$string = "asdf"
$string = substr_replace($string ,"",-1);
JS:
str = "asdf";
str = str.slice(0,-1);
$string = "asdf"
$string = substr_replace($string ,"",-1);
JS:
str = "asdf";
str = str.slice(0,-1);
Thursday, July 9, 2009
AJAX in FB + setTimeout for auto refresh
this is just a simple example of how this JS function, awaits for data coming from PHP script called chat.php and put everything that gets printed there into a div tag with id 'chat':
function chat_refresh() {
var refresh = 1;
var ajax = new Ajax();
ajax.responseType = Ajax.FBML;
ajax.ondone = function(data) {
document.getElementById('chat').setInnerFBML(data);
}
ajax.requireLogin = 1;
var params = {'refresh' : refresh};
ajax.post("chat.php?refresh", params);
setTimeout(chat_refresh, 1000*10);
}
lets say in chat.php?refresh
you print "hello world";
then "hello world" will get printed in between
before:
after:
note:
setTimeout(chat_refresh, 1000*10);
is a function that will automatically call chat_refresh every 10 seconds.
function chat_refresh() {
var refresh = 1;
var ajax = new Ajax();
ajax.responseType = Ajax.FBML;
ajax.ondone = function(data) {
document.getElementById('chat').setInnerFBML(data);
}
ajax.requireLogin = 1;
var params = {'refresh' : refresh};
ajax.post("chat.php?refresh", params);
setTimeout(chat_refresh, 1000*10);
}
lets say in chat.php?refresh
you print "hello world";
then "hello world" will get printed in between
before:
after:
hello world
tags in the HTML page.note:
setTimeout(chat_refresh, 1000*10);
is a function that will automatically call chat_refresh every 10 seconds.
date time difference function in PHP
function dateDiff($dt1, $dt2, $timeZone = 'GMT')
{
$tZone = new DateTimeZone($timeZone);
$dt1 = new DateTime($dt1, $tZone);
$dt2 = new DateTime($dt2, $tZone);
$ts1 = $dt1->format('Y-m-d');
$ts2 = $dt2->format('Y-m-d');
$diff = abs(strtotime($ts1)-strtotime($ts2));
$diff/= 3600*24;
//$diff/=60 if you want to check minutes difference
return $diff;
}
mysql date time and PHP + JS
This is how you get current date time in php:
$dateTime = new DateTime( "now", new DateTimeZone(date_default_timezone_get() ) );
$dt = $dateTime->format("Y-m-d H:i:s");
and this is how to compare it with a row in DB:
$q = "SELECT * FROM ht_chat_logs where TIMESTAMPDIFF(SECOND, time, '$dt') < 0 order by time asc";
it will return all the rows that were created after $dt.
==================================
And this is how you do it in JS:
var currentTime = new Date()
var last_activity = currentTime.getFullYear() + '_' + (currentTime.getMonth() + 1) + currentTime.getDate() + ' ' + currentTime.getHours() + ':' + currentTime.getMinutes() + ' ' + currentTime.getSeconds();
it's gonna return date time in the same format as the one we did in PHP and it's also the same format of mysql timestamp.
$dateTime = new DateTime( "now", new DateTimeZone(date_default_timezone_get() ) );
$dt = $dateTime->format("Y-m-d H:i:s");
and this is how to compare it with a row in DB:
$q = "SELECT * FROM ht_chat_logs where TIMESTAMPDIFF(SECOND, time, '$dt') < 0 order by time asc";
it will return all the rows that were created after $dt.
==================================
And this is how you do it in JS:
var currentTime = new Date()
var last_activity = currentTime.getFullYear() + '_' + (currentTime.getMonth() + 1) + currentTime.getDate() + ' ' + currentTime.getHours() + ':' + currentTime.getMinutes() + ' ' + currentTime.getSeconds();
it's gonna return date time in the same format as the one we did in PHP and it's also the same format of mysql timestamp.
Subscribe to:
Posts (Atom)