is_numeric() And is_int() in PHP

Both is_numeric() and is_int() will return neither TRUE nor FALSE, but null if parameter is null. Logically, it is correct. Practically, it does make these two functions next to useless. Because we human being would never believe null is numeric. For human being, it is obvious...

To make it useful, we would first consider if parameter is null or not, then if it is numeric. Here is simple way to test these three situations once for all:

if (0!=strlen(trim(@$para)) && is_numeric(@$para)) {...};

Trouble with Internet Explorer

The purpose of this article is to establish an uniform convention to deal with a very special issue of IE. It is for sure without this convention, websites would still run with or without problem. The issue is when IE passing null value from JavaScript to PHP, null value becomes string "null". If there is a possibility the user input could be "null", such as using "null" as login name or password, there is no way for PHP to detect which "null" is null and which "null" is input "null".

So, the accurate solution is never let JavaScript passing null to PHP, but using '' instead. It sounds easy; but JavaScript can generate null value without your knowledge. That is, if a parameter passing through a function to feed a form, when original parameter is undefined, eventually that undefined would be become string "null" or string "undefined" at the end of PHP. So, you would need to deal with every form input by special arrangement as follows:

; document.theForm.theInputItem.value = (parameter) ? parameter : ''

Then, to test if it is valid in JavaScript would be changed to:

; if (''!=parameter) {...}

At PHP end, it is relatively easy to detect if it is a valid input:

if (0!=strlen(trim(@$_POST["theInputItem"]))) {...};

However, for numeric data, it is not suitable to use '' instead null. It is still suggested to code as usual. The only difference is at PHP end:

if (0!=strlen(trim(@$_POST["theInputItem"])) && is_numeric(@$_POST["theInputItem"])) {...};


http://koncordpartners.blogspot.com/2009/12/test-various-nothings-in-php.html

Passing JavaScript Array to PHP by Using POST

Passing JavaScript Array to Php is not very popular. However, in some circumstances it becomes necessary; for instance, passing value of a group of checkboxes, using array would be most suitable setting.

In general, passing array is same as passing a variable. In HTML part, it looks:

<input type="checkbox" name="jsArray[1]" value="firstValue">
<input type="checkbox" name="jsArray[2]" value="secondValue">
<input type="checkbox" name="jsArray[3]" value="thirdValue">

The problem happens when HTML codes are generated dynamically or the value of checkbox is assigned dynamically. Normal assignment method, namely document.formName.inputItemName.value = something does not work. There is a suggestion in http://www.it-base.ro/2007/07/27/send-a-javascript-array-to-php/.

Another simply solution is to use id to assign the value:

; document.getElementById('inputItemId').value = something

Easy.

Convert PHP Array to JavaScript Array

<?php
////////////////////////////////////////////////////////////////////////////////////////////
// Universal function used to convert array in PHP to array in Javascript. //
// The result will be in string, includes declaration in Javascript, as well as the value //
// assigned to array in Javascript. //
// The array can be associative, as well as multidimensional, as many multidimensions as //
// you wish. This funcation is particularily useful when the number of elements and level //
// of multidimension is unknown. //
// Parameter $sJS is the string to represent the name of array in JS as you wish. //
////////////////////////////////////////////////////////////////////////////////////////////

function arrayToJavascript($aPHP, $aJS) // This is to deal with first level of recursion.
{
$lenFirst = @count($aPHP); // "@" deals with PHP Error Massage.
if (0!=$lenFirst && is_array($aPHP)) // Test if this is valid array or if reached the end of array.
{
echo "var ".$aJS." = new Array(".$lenFirst.");\n"; // Declare first level of array.
foreach ($aPHP as $key => &$value)
{
if (is_numeric($key))
{
$arrayString = $aJS."[".$key."]"; // Javascript variable.
}
else
{
$arrayString = $aJS."['".$key."']"; // Javascript variable.
};
toJSrecur($arrayString, $aPHP[$key]);
};
}
else
{
echo "Input is not a valid PHP array.";
};
}

function toJSrecur($arrayJS, $element) // This is to deal with standard level of recursion.
{ $len = @count($element); // count() does cause the trouble when reach the end of array.
if (0!=$len && is_array($element))
{
echo $arrayJS." = new Array(".$len.");\n"; // Declare each level of array.
foreach ($element as $key => &$value)
{
if (is_numeric($key))
{
$newString = $arrayJS."[".$key."]"; // Javascript variable.
}
else
{
$newString = $arrayJS."['".$key."']"; // String, is to be used by the echo at next level.
};
toJSrecur($newString, $element[$key]);
};
}
else // Start to write into javascript array at end of each branch in the recursion.
{
if ($element)
{
if (is_numeric($element))
{
$eleValue = $element;
}
else // Sign "'" in Javascript does cause trouble. Escape is needed.
{
$eleValue = "'".str_replace("'", "\'", $element)."'";
};
}
else
{
$eleValue = "''";
};
echo $arrayJS." = ".$eleValue.";\n"; // Assign values when the branch reached the end.
};
}

?>

A Microsoft Usability Bug

in Excel, sometimes the function does not show the calculation result, instead it shows the formula itself. To correct it, one would need to go to Format Cells, change from Text datatype to numerical datatype, such as General.

Technically it is not a bug. In terms of usability, it is. This is because when you change from numerical datatype to text, the calculation still work, until you touched cell, the formula showed up. After that, you won't be able to figure out what went wrong.


http://www.excelforum.com/excel-general/562740-formula-does-not-calculate.html

Code Conventions: Microsoft Access SQL

1. Use original column name as much as possible until last presentative SELECT. This is to help for visual tracing back to where the data come from originally.

2. Never use format [something] as alias for the column, it would cause the visual confusion when you changed idea to reuse it, or extent to next level of expansion. You may use it at last presentative SELECT.

3. Always please comma (,) in front rather than at end of a line. It would enable you to easily conduct visual check, since all lines are started from a command or comma. For instance:

SELECT Col_1
, Col_2
FROM Tab
;

4. Always use your notepad or SQL editor to edit and save file. When complete, copy it onto Microsoft Access. This is because Microsoft Access will rewrite your scripts to make your life much harder. Every time when you need to edit it, open your text file to edit it and then paste it onto Access.

5. Doing your formatting job as much as possible in Access rather than at later stage at Excel or other presentation layer. It is even more important when you make your report automation.

Sequential and Modular Programming

Modular Programming came out as a newer technique. In terms sequence to execute the programing blocks, or called modules, modular programming also means the run time automatically searching where the modules are. Unfortunately, different language sets it differently, some are better and some are not so good. Object-oriented languages are all modular programming and they are the best in this regarding.

PL/SQL

PL/SQL is sequential language and its modules searching function is very bad. It means you would have to put functions/procedures in right order within the package to enable the sequential process. Of course, for packages itself it has no problem since packages are individual files.

Java

Java is a fully object-oriented language, though within the class, it is still the sequential. However, methods within the class are also fully modularized. It means the position of methods plays no role, and can be found by run time automatically.

JavaScript

Although JavaScript is classified as object-oriented language, only functions in root level in the file are modularized. Within the function, while it is sequential, nested functions are not fully modularized. It means within the function, your nested functions need to be placed in right order before it can be called. Even in root level, variablized functions still need to be treated carefully with the order. In particular, some built-in functions are very sensitive to the sequence, such as setTimeout() and setInterval().


http://en.wikipedia.org/wiki/Modular_programming
http://en.wikipedia.org/wiki/Javascript
http://koncordpartners.blogspot.com/2010/04/function-declaration-in-javascript.html

Function Declaration in JavaScript

It is easy to declare a function in JavaScript. And everyone knows it:

Standard or Procedural Function

; function func()
{
...
}

The problem of it is this function cannot be passed as parameter in another function. To be able to do that, you will need to varibalize it:

Varibalized Function, or Function Literal, Function Reference, Function Pointer

; var func = function()
{
...
}

Everyone does that too. Wait a moment. This form for declaration indeed is just set to fail if you use it carelessly. You may get following error massage when sequence to execute programming block becoming sensitive, such as work with setTimeout() and setInvertal() or inside of a function:

[This function] is not defined.

If you include this form of function with setInterval or setTimeout, you may get error message:

useless setInterval call (missing quotes around argument?)

This is because you will need to put it in right sequence to make sure the memory has load the function first.

So, it is suggested in general you should use orthodox function declaration method. If you use variablized function declaration method, please make sure it has been put into right place in the sequence of programming blocks.

Have a look at following case:

; var func = func()

; function func()
{
...
}

No, this is not a function declaration method for first statement. It just get the return value from the function func().

Apart from above mentioned popular method, here is

Function Object

; var func = new Function()
{
...
}

It is not recommended to use because it would take longer time to process, unless for special purpose, such as reconstruct to function from variablized function and variablized parameters. For instance:

; var reconstructedVar = new Function([para1, para2,...paran], functionBody)
{
...
}

Please take note, all parameters and function body must be in string or reference. The other way to reconstruct the function is to do it by yourself. For details, please see Passing Function in JavaScript.


http://www.permadi.com/tutorial/jsFunc/index.html
http://www.hunlock.com/blogs/Functional_Javascript
http://www.dustindiaz.com/javascript-function-declaration-ambiguity/
http://osdir.com/ml/jQuery/2009-11/msg01942.html
Javascript Error Message: is not a function

IF ELSE Statement

The orthodox IF ELSE Statement is IF Condition_1 THEN Function_1 ELSE Function_2. Indeed, this is a simplified statement of: IF Condition_1 THEN Function_1 ELSE IF Condition_2 THEN Function_2. By saying that, the perfect relationship between Condition_1 (C1) and Condition_2 (C2) consists of:

1. The union of Condition_1 and Condition_2 (C1 ∪ C2) covers every possible situations, while
2. they do not have intersection (A ∩ B = 0).

For instances:

Example 1: if(0<C) {F1} else {F2}
Example 2: if(0<C) {F1} else if(0>C) {F2}
Example 3: if(0<=C) {F1} else if(0=>C) {F2}

Example 1 is perfect okay because the implicit Condition_2 covers everything else other than Condition_1. Example 2, however is not such perfect because it does not cover every situations, thus leave a possible logic bug. Example 3 contains logic error because there is intersection between two conditions. It is therefore suggested when use IF ELSE Statement, it shall cover all situations but not overlapped unless you are fully aware what was left behind.

However, when two sets of conditions apply, it because much complicated. For instance:

if(0<C) {F1}
else if(0==C || 100==C2) {F2}
else if(0>C) {F3}
else {F4};

You would never get clear logic set here. Actually, you can, after conditions cover full combinations/metrics of two sets. What about three sets conditions? You should try to avoid this kind of situation. However, if you can't, there is a suggestion:

1. Employ a middle layer, say Action, between Conditions and Functions. Unlike Functions, Actions are just flags of Functions and some of them can override others.
2. Use several IF Statements instead of a single IF ELSE Statement to cover every situations selected by you.
3. Because some Actions may override others, so, careful arranging the orders of IF Statements is necessary.

Here is the example:

if(0==C || 100==C2) {A1};
if(0<C) {A2};
if(0>C || 1!=C3) {A3};
if(0>C) {A4};
if (A1) {F3}
else if (A2) {F1}
else if (A3) {F4}
else {F3};

Done. Just be very careful all necessary situations need to be covered and action overriding order need to be correctly arranged. Else, you just prepare to deal with the logic bugs.

Code Conventions

This is the general one of a serials articles cover different languages.

Bracket

Put opening bracket and closing bracket at same vertical position enabling easier visual check.

Comments

Since full stop/period merely used by any language as ending sign of a statement, it is suggested all comments are to be finished by full stop/period for readiability purpose.

Comparison of IF Statement

Put matched at the left hand side to avoid possible mistake of assignment. For instance:

; if ('String'==varA)

instead of:

; if (varA=='String')

IF ELSE Statement

If there is more than one set of conditions, please use following method to deal with the complex logics:

1. Employ a middle layer, say Action, between Conditions and Functions. Unlike Functions, Actions are just flags of Functions and some of them can override others.
2. Use several IF Statements instead of a single IF ELSE Statement to cover every situations selected by you.
3. Because some Actions may override others, so, careful arranging the orders of IF Statements is necessary.

For detail, please refer to IF ELSE Statement (http://koncordpartners.blogspot.com/2010/04/if-else-statement.html).

Indentation

Use of tabs should be avoided because there still is not a standard for the placement of tabstops. Different code editor will show it differently. The unit of indentation is two spaces, to enable indenting many levels.

What Does Size Mean in Numberic Datatype of MySQL

What does 3 in TINYINT(3) or 11 in INT(11) mean?

It does mean neither bit or byte size of the datatype. The datatype itself has already specified the size of the storage. It is for display purpose. Following paragraphs come from MySQL Manual, http://dev.mysql.com/doc/refman/4.1/en/numeric-types.html:

"Another extension is supported by MySQL for optionally specifying the display width of integer data types in parentheses following the base keyword for the type (for example, INT(4)). This optional display width may be used by applications to display integer values having a width less than the width specified for the column by left-padding them with spaces. (That is, this width is present in the metadata returned with result sets. Whether it is used or not is up to the application.)

The display width does not constrain the range of values that can be stored in the column, nor the number of digits that are displayed for values having a width exceeding that specified for the column. For example, a column specified as SMALLINT(3) has the usual SMALLINT range of -32768 to 32767, and values outside the range allowed by three characters are displayed using more than three characters.

When used in conjunction with the optional extension attribute ZEROFILL, the default padding of spaces is replaced with zeros. For example, for a column declared as INT(5) ZEROFILL, a value of 4 is retrieved as 00004. Note that if you store larger values than the display width in an integer column, you may experience problems when MySQL generates temporary tables for some complicated joins, because in these cases MySQL assumes that the data fits into the original column width. "

To check the size for each of these datatype, please go to same URL: http://dev.mysql.com/doc/refman/4.1/en/numeric-types.html.

Reference:

http://dev.mysql.com/doc/refman/4.1/en/numeric-types.html
http://alexander.kirk.at/2007/08/24/what-does-size-in-intsize-of-mysql-mean/

mod_rewrite Tutorial

First to check if your mod_rewrite is enabled. Check phpinfo.php if you see mod_rewrite, it is enabled. If you do not see it, it is not necessary mean your server is not enabled. You may wish to go to following address to check further: http://www.wallpaperama.com/forums/how-to-test-check-if-mod-rewrite-is-enabled-t40.html

Put it simple, mod_rewrite is just to find a matched string pattern in user’s input URL, and to replace it by the substitution string. So, the center of mod_rewrite is RewriteRule, which is responsible for the match and replace. The rest directives are just for setting purpose. The most used configuration directives other than RewriteRule are RewriteEngine, RewriteOptions.

RewriteEngine’s common value is:
On – This is because default value for this directive is off.

RewriteOptions’ common value is:
Inherit - This forces the current configuration to inherit the configuration of the parent.

RewriteRule’s syntax is:
RewriteRule Pattern Substitution [Flag]

Pattern needs to be bracketed by anchors ^youInputURL$. Pattern consists of two parts, the static substring you known already and those dynamic part. You do not need to change any for static substring, while you would need to group the dynamic part. The grouping can be done by bracket (). There are also two parts inside of (), first is the character class grouping by [], and second is the flag to tell whether the character class has only one character or nil, or more, etc. The character class is ruled by RegExp.

Following is the syntax for the pattern:
(text) - Grouping of text
[chars] - Character class: One of chars
[^chars] - Character class: None of chars
text1|text2 - Alternative: text1 or text2
? - 0 or 1 character of the preceding text
* - 0 or N character of the preceding text
. - 1 character of the preceding text
+ - 1 or N character of the preceding text
\char - escape that particular char, for instance to specify the chars ".[]()" etc.

The substitution consists of two parts, the static string and the dynamic part as grouped in preceding pattern. The second is always shown as $1.

Flag’s syntax is [SOMETHING, SOMETHING, SOMETHING]. SOMETHING is the flag. Following are common used flags:
NC - This makes the input pattern case-insensitive.
L - Stop the rewriting process here and don't apply any more rewriting rules. Use this flag to prevent the currently rewritten URL from being rewritten further by following rules.

Example:
RewriteEngine On
RewriteOptions Inherit
RewriteRule ^([A-Za-z0-9-]+)$ /php/main.php?uname=$1 [NC,L]


http://corz.org/serv/tricks/htaccess2.php
http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html
http://www.yourhtmlsource.com/sitemanagement/urlrewriting.html
http://www.workingwith.me.uk/articles/scripting/mod_rewrite

Copy Only the Structure of A Table

This old little trick had been asked for so many times. So, it might be a good itea to post it on the blog.

In Oracle:

CREATE TABLE NEW_TAB AS
SELECT *
FROM OLD_TAB
WHERE 0 = -1

In SQL Server:

SELECT *
INTO NEW_TAB
FROM OLD_TAB
WHERE 0 = -1

The key point is WHERE condition. Because this condition is never to be met, so there is no records actually being selected. Someone might like WHERE 1 = 2, however, 1 or 2 can be referred to column one and column two. If by chance the value in column one just equals to column two, haha, you will get some data.

Strange Behavior Between onkeydown And onkeypress Events

A strange behavior between onkeydown and onkeypress events in JavaScript has been noticed. Here is a function to find out the keycode:

; function getCode(e)
{
; var evt = window.event ? event : e
; var code
; if(window.event) code = evt.keyCode
else code = evt.which
; return code
}

If the event is onkeypress, this function would generate ASCII key code. However, if the event is onkeydown, this function would generate JavaScript keycode, which does not discriminated the cases. Indeed, the latter generate keycode for capital case only.

Passing Function in JavaScript

To pass function like a reference, one needs first to make the function a variable reference:

; var funcationName = function(argu) { ... }

Then, it can be passed:

; function anotherFunc(passingFunc)
{
; passingFunc(para)
}

Use it just like the function itself. Indeed, if there is no parameter for functionName(), you will still need to use it as function:

; function anotherFunc(passingFunc)
{
; passingFunc()
}

Function passing even can be used to across the html pages, just like variable reference passing:

; function anotherFunc(passingFunc)
{
; parent.passingFunc()
}

In HTML, following syntax is used to invoke the function:

onkeypress="anotherFunc(funcationName)"

It is very important, the sign of () could NOT be put in invokin statement in HTML, something like:

onkeypress="anotherFunc(funcationName())"

Now, this syntax does create confusion when you want to pass the parameter as will, for instance, you want to call anotherFunc(funcationName(argu)). The ways to overcome it is:

1. For static passing function with dynamic passing varialbe: Declare argu as global variable. Codes are as follows:

; var para

; var funcationName = function(argu) { ... }

; function anotherFunc(passingFunc)
{
; passingFunc(para)
}

onkeypress="para=something;anotherFunc(funcationName)"

3. If you want a complete dynamic passing function together with a dynamic passing variable, you will need to create third function:

; var para

; var funcationName = function(argu) { ... }

; var thirdFunc = function()
{
...
; funcationName(para)
...
}

; function anotherFunc(passingFunc)
{
; passingFunc()
}

onkeypress="para=something;anotherFunc(thirdFunc)"

Function thirdFunc() indeed is where you should play with.

Another approach is to write a function to reconstruct the function from variables:

; function reconstructFunc(func, totalPara, para1, para2, para3)
{
; var newFunc
; if (0==totalPara) newFunc = func
else if (1==totalPara)
{
; newFunc = function()
{
; func(para1)
}
}
else if (2==totalPara)
{
; newFunc = function()
{
; func(para1, para2)
}
}
else
{
; newFunc = function()
{
; func(para1, para2, para3)
}
}
; return newFunc
}

It is very important when passing function, the function must be properly declared. Please refer to http://koncordpartners.blogspot.com/2010/04/function-declaration-in-javascript.html. This article also covers another method to reconstruct the function from variablized function and parameters.

If the function reference/literal had passed across HTML pages, in IE 8 it might general error as "Function expected". To overcome this, you need to set up a local variablized function to call access remote function.

How to Enforce Download of JavaScript File

When debugging javascript file, it is necessary for browser to download the javascript file everything. However, the browser won't. Indeed it is the beauty of the technology because it saves a lot of traffic time. You can't complaint it. What you can complaint is why the browser's designer does not include a special key for user to decide when the javascript file should be downloaded.

Let us face the reality now. If your javascript debugging tool does not do it for you, there are several ways to do it. For instance, you can change javascript file name each time, you can also add version number to it, or you can even change the directory for every version. The problem here is you will also need to change the code in head section of html file. It is not fun after all.

Here is the suggestion. If your problem does not have php back end, use change file name option. Put a version number directly after the name, like: jsname01.js, janame02.js, jsname03.js, etc.

If you have php back end, you can wrap your js file by php. Here is the method:

1. Change your jsname.js file to jsname.js.php.

2. At the beginning of the file, add:

<?php
print
<<<NOWDOC

At the end of the file, add:

NOWDOC;
?>

3. Change all your javascript open comments from // to <!-- ... -->. It would cause the trouble for open comments in .js.php file. For more information on javascript comments, please refer to Code Conventions: JavaScript.

4. Change your html head to: <script language='Javascript' src='filename.js.php' type='text/javascript'></script>.

5. When ready to deploy, change all these back.

I call this PHP Wrapping JavaScript Debugging Method.

Error Message: XML cannot be the whole program

Error message "XML cannot be the whole program" appears when load a javascript file which was generated by PHP file. It actually has nothing to do with its appearance. There are two possible causes:

1. The file contains <script> and </script>. These two scripts indeed are unnecessary because in your html file, it had been already included: <script language='Javascript' src='filename.js.php' type='text/javascript'></script>.

2. Your php code is not clean. It contains some form of invisiable editorial codes inserted by your editor, such as Notepad, etc.

Code Conventions: JavaScript

Organizing

There can be six major parts:

1. Passing Variable Register: This is to register any variable across the HTML files. Do not use crossing file variable directly in body of JavaScript, instead declare here. For instance:

; var localVar = parent.superVar

2. Passing Function Register: To register the functions calling other functions located in different HTML file. Do not call crossing file function directly in body of JavaScript, instead declare here. For instance:

; function closeProcess()
{
; parent.closing()
}

Put Passing Variable Register and Passing Function Register at top of JavaScript file to enable easier updating during coding phrase.

3. Local Global Variable Declaration.

4. Event Functions: Include all event functions here, such as onload, etc.

5. HTML Action Functions: If the function is called by HTML file, initialized by the user, it should be included here.

6. Internally Called Functions: Functions called by event functions or action functions.

End of Statement

JavaScript allows the developer to decide whether or not to end a line with a semicolon. If the semicolon is not provided, JavaScript considers the end of the line as the end of the statement. It is suggested to use semicolon instead of nature line break. Furthermore, you can indeed use semicolon in front of each statement, not only emphasis the line break, but also to increase visual impact on the indentation. All examples in this post are in this format.

Comments

It is suggested to use closed comments tag as much as possible: <!-- -->. By doing this, it would be relatively easier to keep coding parts clearer. In addition, if you are using PHP Wrapping JavaScript Debugging Method, as introduced here:
http://koncordpartners.blogspot.com/2010/04/how-to-enforce-download-of-javascript.html, it is essential to use the closed comments.

DHTML

Use + to concatenate every line of HTML codes, such as:

; var htmlBody = ''
+ ' <table> ...
+ ' <tr> ...

Whitespace within string serves no purpose for HTML. However, it can make visual alignment for coding purpose.

Function Declaration

Always use most orthdox variablized function declaration:

; funcation func()
{
...
}

Avoid to use variablized function declaration like var func = function() {...}, unless it is necessary. If you do use variablized function declaration, make sure it had been placed before the caller. For details please see http://koncordpartners.blogspot.com/2010/04/function-declaration-in-javascript.html.

Form With PHP Behind

Use '' instead of null. Accordingly, the PHP end should be:

if (0!=strlen(trim(@$_POST["theInputItem"]))) {...};

When use function to assign value to form, string parameter would need to be assigned with '' in consideration of it might be null or undefined:

; document.theForm.theInputItem.value = (parameter) ? parameter : ''

For details, please refer to http://koncordpartners.blogspot.com/2010/04/trouble-with-internet-explorer.html.


http://javascript.crockford.com/code.html

Labels