Wednesday, 29 June 2011

Remove the back slashes from String or DB

string stripslashes ( string $str )
 eg:
$stripped = 'this is a string with three\\\ slashes';
$stripped =  stripslashes($stripped);


  Output: 'this is a string with three\ slashes'



Double stripslashes to completely remove 3 consecutive slashes

Tuesday, 28 June 2011

Insert string with single quote (') in DB

string addslashes ( string $str )

For example, to insert the name O'reilly into a database, you will need to escape it.

<?php
$str 
"Is your name O'reilly?";// Outputs: Is your name O\'reilly?echo addslashes($str);?>
 
This would only be to get the data into the database, the extra \ will not be inserted. 

Wednesday, 1 June 2011

Leading zero to numbers in PHP

Here's a simple code snippet to add leading zero to a number. How to add leading zero to date

#1

<?php 
function leadingzero ($num,$fill) { 
 while (strlen($num)<$fill) { 
         $num = "0".$num;
    }
    return $num; 
}
echo leadingzero(100, 3);
?>


Output: 000100

#2

<?php
$x = 1;
$y = sprintf("%03d",$x);
echo $y;
?>

Output: 001

#3

Print a day in double digit; Leading zero for first 9 days.

<?php
for ($num = 1; $num <= 31; $num++) {
if($num<10)
$day = "0$num"; // add the zero
else
$day = "$num"; // don't add the zero
echo "<p>$day</p>";
}
?>

Output:

01
02
03
04
05
06
07
08
09
10
.
.
.
31