Nice one liner to restore a database

zcat `ls -t *.gz | head -1` | mysql -uroot -ppassword DB_NAME

The above runs a command ls -t to show files in a directory, order by modification time -t, it then just grabs the first one in the list head -1 i.e. the latest back up file. The output is then piped to mysql where the SQL is ran.

Javascript string filtering methods

Some maybe useful Javascript string manipulation and filtering methods:

// convert Characters
returnString = returnString.replace(/ö/g, 'o');
returnString = returnString.replace(/ç/g, 'c');
returnString = returnString.replace(/ş/g, 's');
returnString = returnString.replace(/ı/g, 'i');
returnString = returnString.replace(/ğ/g, 'g');
returnString = returnString.replace(/ü/g, 'u');

// if there are other invalid chars, convert them into blank spaces
returnString = returnString.replace(/[^a-z0-9\s-]/g, "");
// convert multiple spaces and hyphens into one space
returnString = returnString.replace(/[\s-]+/g, " ");
// trims current string
returnString = returnString.replace(/^\s+|\s+$/g,"");
// cuts string (if too long)
if(returnString.length > maxLength)
    returnString = returnString.substring(0,maxLength);
// add hyphens
returnString = returnString.replace(/\s/g, "-");
/**
  * Remove all characters that do not fit regex antipattern.
  *
  * @param string $string
  * @param string $antiPattern
  **/
function stripInvalidStringChars($string, $antiPattern) {
    return preg_replace('/ {2,}/',' ',preg_replace($antiPattern, '', $string));
}

PHP – Validate an array of integers in one go

Here’s a nice way to make sure an array of integer values contains elements that are greater than zero.

$array = array(123,32,321,3442,342);
$r = array_filter($array, create_function('$val', 'return (int)$val;'));
if(count($array) != count($r)) {
  echo 'not valid';
}else {
  echo 'valid';
}

MySQL Count Rows For Pagination

The following SQL snippet shows a neat way to do queries when implementing paged results.

I have tested the snippet on MySQL 5 only.

SELECT SQL_COUNT ROWS *, tableName.id, tableName.someCol
FROM tableName
LIMIT 0,25;

Read the rest of this entry »

PHP Boolean Rules

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string “0″
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

More information here