Saturday, 24 September 2011

Making dyanamic variable in CSS


Using PHP to generate a CSS file.
One advantage of CSS is that your styles can be kept in a separate file from the pages that use them. This is simply a text file that ends with the .css suffix such as style.css. The suffix tells the server to treat the contents of the file as CSS. Unfortunately, the CSS standard doesn’t allow for variables within a .css file. The solution is to use a PHP file, such as style.php and include code to let the server know that the contents of the file should be treated as CSS. This can be accomplished by including the following line of PHP at the top of the style sheet;
<?php header(“Content-type: text/css”); ?>
Your style definitions can then follow so that the top of your style.php document looks something like this:
<?php header(“Content-type: text/css”); ?>
a:link { text-decoration : none; color : #FF0000; }
a:active { text-decoration : underline; color : #FF0000; }
a:visited { text-decoration : none; color : #FF0000; }
a:hover { text-decoration : underline; color : #660000; }
Your .php style sheet will now function exactly like a .css one. We’ll get to the variables in a minute but first…
Linking to your .php style sheet
You can link to your .php style sheet exactly as you would a regular style sheet. Here’s the code I placed in the <head> section of my webpage:
<link href=”style.php” rel=”stylesheet” type=”text/css” />
Using variables in your style.php file
The advantage of a PHP style sheet is that it allows you to define variables and then use those variables throughout your style sheet. So, for the example I gave above where the a:link, a:active and a:visited styles all use the same color (#3366cc), we could define a “$linkColor” variable (The “$” before linkColor simply indicates it is a variable.) and use it in all three styles. The variable definition would look like this:
<?php header(“Content-type: text/css”);
$linkColor = ‘# #FF0000;
?>
Remember all PHP code must be contained within a php tag which opens with “<?php” or simply “<?” and closes with “?>”
We can now insert the variable into our css code like this:
<?=$linkColor?>
Notice the opening and closing php tags.
So the beginning of our CSS file now looks like this:
<?php header(“Content-type: text/css”);
$ linkColor = ‘#FF0000;
?>
a:link { text-decoration : none; color : <?=$ linkColor?>; }
a:active { text-decoration : underline; color : <?=$ linkColor?>; }
a:visited { text-decoration : none; color : <?=$ linkColor?>; }
a:hover { text-decoration : underline; color : #000021; }
Now to change the color of the a:link, a:active and a:visited links from red (#FF0000) to blue (#0000FF) we need only change the definition of $linkColor:
<?php header(“Content-type: text/css”);
$ linkColor = ‘#0000FF;
?>
A word about variables and variable names
It should be easy to see how this trick can make editing your style sheets a lot easier. What’s less obvious (at least initially) is that, if you create a variable for every possible style, your variable list will soon become nearly as complicated and confusing as your original style sheet. Here are a couple tips to keep things simple:
  1. Build your color palette carefully so that you can color as many pieces of the design as possible using the same variable. For instance, if your header, footer and sidebar will be the same color, you can use the same variable (perhaps $secondColor) to define them.
  2. Don’t be too specific with your variable names. You don’t want to use the variable name $red, if you might be changing it to blue later on. Similarly, you probably don’t want to use the variable name $headerColor if the variable is also used for the footer and sidebar. I prefer names such as $themeColor, $hiliteColor, etc.
  3. Plan carefully so that you don’t force yourself into a situation where your type and background have insufficient contrast. In spite of #1 above, you might sometimes need to define more than one variable with the same color to provide future flexibility.
  4. Use PNG graphics for images that are partially transparent. Since PNGs offer true transparency, you can create a drop shadow that will work over any background color. That’s important if you’ll be changing those background colors. Just remember, you need to use a png javascript fix for PNGs to display properly in Explorer 6.


NOTE:
header(’Content-type: text/css’); seems to cause problems for Safari. Try this instead:
header(”Content-Type: text/css; charset: utf-8?);


Thursday, 22 September 2011

PHP Mailer Tips

Adding CC in phpmailer

 $mail->AddCC('test@test.com, 'Admin');


Friday, 16 September 2011

disabling auto logoff on phpmyadmin

http://www.phpmyadmin.net/documentation/

 In the file libraries/config.default.php

change the value for LoginCookieValidity
/*
* Prevent timeout for a week at a time.
* (seconds * minutes * hours * days)
*/
$cfg['LoginCookieValidity'] = 60*60*24*7;




Thursday, 15 September 2011

Displaying a Multidimensional Array using For each

<?php
  $emp_det = array (array (Name=>"a", Code=> "8", Hobby=> "A"),
                    array (Name=>"b", Code=> "8", Hobby=> "B"),
                    array (Name=>"c", Code=> "1", Hobby=> "C"),
                    array (Name=>"d", Code=> "3", Hobby=> "D"),
  );
  foreach ($emp_det as $tempone) {
    foreach ($tempone as $key=>$temptwo) {
      echo "$key: $temptwo""\n";
    }
    echo "\n";
  }
?>

Tuesday, 6 September 2011

Colorbox Tips

Opening colorbox popup using function:

<script>
function lightbox(){    
  $.fn.colorbox({width:"80%", height:"80%", iframe:true, href:"/pagetoopen.html"});
}
</script>
<input type="button" value="open the box" onClick="lightbox()"/>

Modify above function to refresh the parent page when popup closed:

$.fn.colorbox({width:"95%", height:"95%", iframe:true, href:"allocate-contact-number.php?id="+checked_num, onClosed:function(){window.location.reload();}});


Close popup 


<script type="text/javascript" >

self.parent.$.fn.colorbox.close();
</script>





Thursday, 1 September 2011

Displaying javascript running clock time for selected timezone


<?php
$timeFormat = $_SESSION["display"]["php_time_format"];

$currentTime_client = parse_date_for_clock($_SESSION["timezone"], $connA);
$currentTime_system = date("F d, Y ".$timeFormat);

if($timeFormat=="h:i:s A"){
    $clockFormat = "12";
}else{
    $clockFormat = "24";
}
?>
<script type="text/javascript">

var serverDate_client;
var serverDate_system;

function getServerDate_client(){
serverDate_client=new Date("<?php echo $currentTime_client;?>");
}
function getServerDate_system(){
serverDate_system=new Date("<?php echo $currentTime_system;?>");
}

function tick(timeFormat,showTimeFor,showTimeDiv){
if(showTimeFor=="client"){
    serverDate=serverDate_client;
}else{
    serverDate=serverDate_system;
}


serverDate.setSeconds(serverDate.getSeconds()+1);
var currentHours = serverDate.getHours();
var ampm="";
if(timeFormat=='12'){
if(currentHours >=12){
    ampm="PM";
}else{
    ampm="AM";
}
currentHours = (currentHours > 12 ) ? currentHours - 12 : currentHours;
currentHours = (currentHours == 0 ) ? 12 : currentHours;

}
if (currentHours<10) currentHours="0"+currentHours;

var min = serverDate.getMinutes();
if (min<10) min="0"+min;
var sec = serverDate.getSeconds();
if (sec<10) sec="0"+sec;
document.getElementById(showTimeDiv).innerHTML = currentHours + ":" + min + ":" + sec+" "+ampm;
}

window.onload=function(){
getServerDate_client();
setInterval("tick('<?php echo $clockFormat;?>','client','client_clock')", 1000);
getServerDate_system();
setInterval("tick('<?php echo $clockFormat;?>','system','system_clock')", 1000);
}
</script>



======== php time function definition used in above script==========
function parse_date($gmtoffset, $connA) {// parse date and time both

        $currdate = date("Y-m-d H:i:s");
        return mysql_fetch_object(mysql_query("SELECT DATE_FORMAT(CONVERT_TZ('$currdate', '".date("P")."', '$gmtoffset'), '".$_SESSION["display"]["mysql_date_format"]." ".$_SESSION["display"]["mysql_time_format"]."') AS display_date", $connA))->display_date;
    }

    function parse_date_only($gmtoffset, $connA) {

        $currdate = date("Y-m-d H:i:s");
        return mysql_fetch_object(mysql_query("SELECT DATE_FORMAT(CONVERT_TZ('$currdate', '".date("P")."', '$gmtoffset'), '".$_SESSION["display"]["mysql_date_format"]."') AS display_date", $connA))->display_date;
    }
    function parse_time_only($gmtoffset, $connA) {

        $currdate = date("Y-m-d H:i:s");
        return mysql_fetch_object(mysql_query("SELECT DATE_FORMAT(CONVERT_TZ('$currdate', '".date("P")."', '$gmtoffset'), '".$_SESSION["display"]["mysql_time_format"]."') AS display_date", $connA))->display_date;
    }

    function parse_date_for_clock($gmtoffset, $connA) {

        $currdate = date("Y-m-d H:i:s");
        $format = "%M %d %Y ".$_SESSION[display][mysql_time_format];
        return mysql_fetch_object(mysql_query("SELECT DATE_FORMAT(CONVERT_TZ('$currdate', '".date("P")."', '$gmtoffset'), '$format') AS display_date", $connA))->display_date;
    }

Bulk data insertion in mysql and PHP


$conn = mysql_connect("localhost", "root", '111111', false, 65536)or die(mysql_error());

$studentName = array("Rahul", "Ravi", "Sachin", "Vikas","Sunidhi");

foreach($studentName as $value){

$query_arr[] = "(NOW(),NOW(),$value)";
}


$bulk_ins_qry = "INSERT INTO tbl_student (creationdate,lastupdate,name)
                    VALUES";

$bulk_ins_qry .= implode(",",$query_arr);
mysql_query($bulk_ins_qry, $conn);




Wednesday, 17 August 2011

Important tips about webserver.

Command to calling a php file during Setting a cron job on Cpanel

lynx -source http://www.yourdomainname.com/crons/cron-jobs.php

Saturday, 13 August 2011

Ajax request form

function submit_register(form)
{
    var strSubmit       = '';
    var formElem;
    for (i = 0; i < form.elements.length; i++) {
        formElem = form.elements[i];
        switch (formElem.type) {
                case 'text':
                case 'select-one':
                case 'hidden':
                case 'password':
                case 'textarea': strSubmit += formElem.name + '=' + escape(formElem.value) + '&'; break;
        }
    }
    
    ajaxReq.open('POST',  http+'/cart/register-data-page.php?req='+Math.random(), true);
    ajaxReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajaxReq.onreadystatechange = function() {
            if (ajaxReq.readyState == 4) {
                  alert(ajaxReq.responseText);
            }
    }
    ajaxReq.send(strSubmit);
    return false;}

Friday, 12 August 2011

General Javascript functions

Clear the content of an div or span after a specific time:


function clrDiv(div2clr){
document.getElementById(div2clr).innerHTML = "";

}


Input: div or span id from which content has to be removed

Usage Example:
var resultDiv = 'mydivID';
var clr = setTimeout("clrDiv('"+resultDiv+"')", 2000);

 Insert Text at Cursor

function addText( input, insText ) {
        input.focus();
        if( input.createTextRange ) {
            document.selection.createRange().text += insText;
        } else if( input.setSelectionRange ) {
            var len = input.selectionEnd;
            input.value = input.value.substr( 0, len )
            + insText + input.value.substr( len );
            input.setSelectionRange(len+insText.length,len+insText.length);
        } else { input.value += insText; }
    }
 
 
PHP Equivalent in_array function in javascript: 

Array.prototype.in_array = function(p_val) {
 for(var i = 0, l = this.length; i < l; i++) {
  if(this[i] == p_val) {
   return true;
  }
 }
 return false;
}

Usage:

var weekdays ="sunday,monday,tuesday,wednesday,thursday,friday,saturday";
weekDayArr = weekdays.split(",");
 
if(weekDayArr.in_array('sunday'))
{
   alert("Sunday found");
}else{
 alert("sunday not found");
}
 
 
 
// Deafault input text swap



    function clearbox(box,defaulttxt) {





        if(defaulttxt.toLowerCase() == box.value.toLowerCase()) {

            box.value = "";

        }



        box.onblur = function() { unclearbox(box,defaulttxt);}



    }



    function unclearbox(box,defaulttxt) {

        if(box.value == "") {

        box.value = defaulttxt;

        }

    }
 

Select a drop down value using like search

<form name="myform" action="" method="POST">
<div>
    <select name="country">
        <option value="india_91">India</option>
        <option value="australia_23">Australia</option>
        <option value="china_56">China</option>
    </select>
</div>
<div>
    <input type="text" value="" onblur="setSelectedIndex(country, this.value)">
</div>
</form>
<script language="javascript">
    
function setSelectedIndex(s, v) {
    for ( var i = 0; i < s.options.length; i++ ) {
        var found = s.options[i].value.indexOf(v);
        if(found != "-1") {
           s.options[i].selected = true;
         return;
        }
    }
}

</script>


SMS counter with block and text counter:


function smsTextCounter(fieldID,resultID,maxlimit) {
  var smsBlock;
  var currentLength = document.getElementById(fieldID).value.length;
  smsBlock = Math.ceil(currentLength/maxlimit);
  document.getElementById(resultID).innerHTML = (maxlimit*smsBlock) - currentLength+"/"+smsBlock;
  if(currentLength==""){
      document.getElementById(resultID).innerHTML = maxlimit+"/"+1;
  }
}

Usage:
<tr class="form-row-1">
        <td width="40%" align="right" valign="middle" class="form-txt-no-border" <?php echo $tbl_row_hght;?>>Message:</td>
        <td width="60%" align="left" valign="middle">
        <textarea name="message" id="message" class="input" rows="10" cols="50" onkeyup= smsTextCounter('message','msgCounter','160') ></textarea></td>
      </tr>
      <tr>
      <td align="right" valign="middle" <?php echo $tbl_row_hght;?>></td>
      <td align="left" valign="middle" id="msgCounter" class="form-txt-no-border">160/1</td>
      </tr>

Inserting serial number in a table list:

function addSerial(tableID,serialStartFrom) {
    
    var rows = document.getElementById(tableID).rows, // get the rows in the table
    len = rows.length,    // get the quantity of rows
    cell = 1,             // index of the column (zero based index)
    count = serialStartFrom;            // keep score

    for(var i=0;i<len; i++){
       rows[i].cells[cell].innerHTML=count;
        count++;
       
    }    
}
setInterval("addSerial('voiceFiles',1)",500);


Giving alternate color to table listing:

function alternate(id){
  if(document.getElementsByTagName){
    var table = document.getElementById(id);
    var rows = table.getElementsByTagName("tr");
    var rowCounter=0;
    for(i = 0; i < rows.length; i++){
       if(rows[i].style.display !="none"){
      if(rowCounter % 2 == 0){
       rows[i].className = "form-row";
       }else{
       rows[i].className = "form-row-1";
            }
            rowCounter++;
          }
        }
         }
        }

usage:
document.onload=alternate("tableID");





Form validation in javascript

To check whether a radio button is checked or not:


function is_radio_checked(theForm,fieldname){
    var n=0;
    var rads =theForm.elements[fieldname];
    var valuee="";
    for(var i=0;i<rads.length;i++){
      if(rads[i].checked==true){
         valuee=rads[i].value;
         n=n+1;
      }
    }
    if(n==0){
      return false;
    }else{
      return selectedSingleValue;
    }
}

Input: Form name and name of radio field
Output: It will return the selected radio value and false if no radio is selected
Usage Example:

function checkform(theForm){
    if(is_radio_checked(theForm,'invoice_payment_statusID')==false){
        alert("Please select at least one option from status.");
        return false;
    }
}

=========== Importing value from pop up window to parent window===
function importAddress()
{


    var flag=0;
    val=new Array();
    var c=0;
    for (var i=0; i < document.form1.elements.length; i++)
    {

        if(document.form1.elements[i].name=='referID[]' && document.form1.elements[i].checked==true){
            flag=1;

            val[c]=document.form1.elements[i].value;
            c++;

        }

    }

    if(flag==0){
        window.close();
    }else{
        var selvalue =  val.join(",");
        window.opener.document.getElementById('recepient').value = selvalue;
        window.close();
    }

}

Monday, 8 August 2011

Javascript trim functions

Javascript Trim LTrim and RTrim Functions

Description

This set of Javascript functions trim or remove whitespace from the ends of strings. These functions can be stand-alone or attached as methods of the String object. They can left trim, right trim, or trim from both sides of the string. Rather than using a clumsy loop, they use simple, elegant regular expressions. The functions are granted to the public domain.

Javascript Trim Member Functions

Use the code below to make trim a method of all Strings. These are useful to place in a global Javascript file included by all your pages.

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+myString.trim()+"*");
alert("*"+myString.ltrim()+"*");
alert("*"+myString.rtrim()+"*");

Javascript Trim Stand-Alone Functions

If you prefer not to modify the string prototype, then you can use the stand-alone functions below.

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+trim(myString)+"*");
alert("*"+ltrim(myString)+"*");
alert("*"+rtrim(myString)+"*");

Example

Type in the box below and you will see the trimmed output dynamically. You must enter spaces before and after the string to see a difference. All whitespace is removed, including tabs and line feeds.
-----------------------------------------------------------------------------------

Compatibility

The functions above use regular expressions, which are compatible with Javascript 1.2+ or JScript 3.0+. All modern (version 4+) browsers will support this. If you require functions for older versions of Javascript back to version 1.0, try the functions below adapted from the Javascript FAQ 4.16. These strip the following, standard whitespace characters: space, tab, line feed, carriage return, and form feed. The IsWhitespace function checks if a character is whitespace.

function ltrim(str) { 
	for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++);
	return str.substring(k, str.length);
}
function rtrim(str) {
	for(var j=str.length-1; j>=0 && isWhitespace(str.charAt(j)) ; j--) ;
	return str.substring(0,j+1);
}
function trim(str) {
	return ltrim(rtrim(str));
}
function isWhitespace(charToCheck) {
	var whitespaceChars = " \t\n\r\f";
	return (whitespaceChars.indexOf(charToCheck) != -1);
}

Saturday, 16 July 2011

Very helpful User defined PHP functions

Function to seprate prefix and phone number from the given phone number


<?php
$prefix=454;// prefix from database
$number = 45454545454;// number including prefix

function seprateNumberAndPrefix($prefix, $number){
    $prefixLength=strlen($prefix);
    $prefixInNumber = substr($number, 0,$prefixLength);
    if($prefix==$prefixInNumber){
       return $str = $prefix."_".substr($number, $prefixLength);
    }
}
echo seprateNumberAndPrefix($prefix, $number);
?>



------------------------------------------------------------------------------------------
Check for whole decimal number

function isWholeDecimal($number){
    $numberArr = explode(".", $number);
    $firstPart = $numberArr[0];
    $secPart = $numberArr[1];
    if($secPart>0){
    }else{
        $number = $firstPart;
    }
    return $number;       
}

------------------------------------------------------------------------------------------

Function to download files from server:


function downloadFile($filename){
$filename = str_replace("./","",str_replace("../","",$filename);// it is to prevent hackers to append file path

// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression')){
  ini_set('zlib.output_compression', 'Off');
}

$file_extension = strtolower(substr(strrchr($filename,"."),1));
if( $filename == "" )
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
  exit;
} elseif ( ! file_exists( $filename ) )
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
  exit;
};

switch($file_extension)
{
  case "pdf": $ctype="application/pdf"; break;
  case "exe": $ctype="application/octet-stream"; break;
  case "zip": $ctype="application/zip"; break;
  case "doc": $ctype="application/msword"; break;
  case "xls": $ctype="application/vnd.ms-excel"; break;
  case "csv": $ctype="application/vnd.ms-excel"; break;
  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  case "gif": $ctype="image/gif"; break;
  case "png": $ctype="image/png"; break;
  case "jpeg":
  case "jpg": $ctype="image/jpg"; break;
  default: $ctype="application/force-download";
}

header("Content-Description: File Transfer");
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
ob_clean();
flush();
readfile($filename);
exit();
}


Input: File name with full path:
Example:  downloadFile("/var/www/html/uploads/test.php");


Redirecting the page after record updation or deletion :

function self_redirect($msg){
    $currentPage = basename($_SERVER['PHP_SELF']);
    $_SESSION['succmsg'] =$msg;
    header("Location:$currentPage");
    exit();
}

get success message for display

function succmsg(){
    $succmsg = $_SESSION['succmsg'];
    unset($_SESSION['succmsg']);
    return $succmsg;
}

Make url and email link clickable in message body:

<?php
function  autolink($message) {
    //Convert all urls to links
    $message = preg_replace('#([\s|^])(www)#i', '$1http://$2', $message);
    $pattern = '#((http|https|ftp|telnet|news|gopher|file|wais):\/\/[^\s]+)#i';
    $replacement = '<a href="$1" target="_blank">$1</a>';
    $message = preg_replace($pattern, $replacement, $message);

    /* Convert all E-mail matches to appropriate HTML links */
    $pattern = '#([0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.';
    $pattern .= '[a-wyz][a-z](fo|g|l|m|mes|o|op|pa|ro|seum|t|u|v|z)?)#i';
    $replacement = '<a href="mailto:\\1">\\1</a>';
    $message = preg_replace($pattern, $replacement, $message);
    return $message;
}
// Usage
$message="For more information visit http://www.google.com or dummyuser@kjkjkjkjkjk.com";
$message = autolink($message);
echo $message;
?>




Wednesday, 15 June 2011

PHP function to prevent mysql injection

function dbSafe($data){
    global $connA;
    if(!empty($data)){
        if(get_magic_quotes_gpc()){
            $data=mysql_real_escape_string(trim(stripslashes($data)),$connA);
        }else{
            $data=mysql_real_escape_string(trim($data),$connA);
        }
        if(empty($data)){
            die("Error: DB connection fail for dbSafe().");

        }
    }
    return $data;
}

// here $connA is database connection.

Using foreach to fetch form data

foreach($_POST as $formLable=>$formValue){
  if(!empty($formValue)){
    if(is_array($formValue)){
        $formValue=dbSafe(implode(",", $formValue));
    }else{
        $formValue=dbSafe($formValue);
    }
     ${$formLable}  = $formValue;
  }else {
    ${$formLable}  = "";
  }
}

Thursday, 9 June 2011

PHP debugging tips

BETWEEN operator is not working in MYSQL:

1. Check the field type it must be datetime
2. please check that in between first date must be less than second date

2.mysql_real_escape_string not working with trim:
please check that trim must be inside the mysql_real_escape_string

Problem in posting form
nested form

Everything is fine but script is unable to run

try to change short php tags to standard php tags

i.e. <? to <?php and <?= to <?php echo
 change some apache server not support short tags

My script is not going in the given if condition even if condition satisfy

if it is comparison then check for proper assignment sign.
It may possible that you have used = instead of ==

Commands out of sync; You can't run this command now

close the connection and then make same connection again

style padding is not working in html

check you have also given align ="" attribute to td.
align and padding not work simultaneously

First my script was working finely but now suddenly it stops working:

1. check the folders name. It may be possilbe that inclusion path have been changed asyou have rename some folder.
2. check whether you have checked database name, or table name, or change the coloumn type , size,

All is fine but multiple selected value of checkbox array return empty array

1. Don't use mysql_real_escape_strings with array field while retrieving this value from form.
2. Have you used name as array while fetching the POSTED value.
e.g.: country as country[]

strpos not working

It is a different function so be careful while using it.
Point to be noted:
1. This functions returned value can be compared by "===" operator and not with "==" as usual we do normally.
2. All function return a definite value but this is not true for this function:
it may return: either "0" or "false" or ""
so you have apply validation for all these three cases in case of false condition of this function.


Unable to upload file

1. Have you define enctype in form tag
2.Folder permission of the folder in which file has been uploaded must be "777"
3.File size of the file to be upload must be within the upload limit

Did not find any bug but phpmyadmin is showing error in query

1. Please check that wether table name and field name must be different.
2. Coloumn name should not have the name which are reserved keyword for mysql (e.g many people used desc for description but desc is reserved keyword for DESCENDING ORDER in mysql)

 Switch case is giving wrong result
 
  1. Are you sure you have use break after all cases.

I could not understand why Everything is ok but only Partial value is inserted in the database table ?

  Have you check the field length of this field in database table. It may be possible that you have defined less field length.


I have made a php function to in which mysql query has been used, everything is ok but query is not executed.

You cannot access database connection variable directly in a function.Please check either you used "global  $conn" or
Have used database connection variable as a function parameter.

Wednesday, 8 June 2011

Modified print_r function in php

Modified print_r function

function print_rr($in){
        echo "<pre>";
        print_r($in);
        echo "</pre>";
}

Usage: print_rr(Array);

Replace a password with * along with some readable text

Some times we need to display some numbers (like bank account number or password) in partial form. We can use following to functions to do it.

1. PHP function to replace a password with *  alogn with some readable prefix (e.g. 5987***)

function hideRight($str,$prefixLen){
    $strLen = strlen($str);
    $passPrefix = substr($str,0,$prefixLen);
    $newStr="";
    for ($i=$prefixLen; $i<$strLen; $i++){
         $newStr .="*";
    }
        $newStr = $passPrefix.$newStr;
        return $newStr;
 }

usage:
$input = "35468452";
$output =  hideRight($input,'2');
//output will be 354684**




2. PHP function to replace a password with *  alogn with some readable suffix (e.g. ****5987)

 function hideLeft($str,$suffixLen){
    $strLen = strlen($str);
    $suffix = substr($str,-$suffixLen);
    $newStr="";
    for ($i=$suffixLen; $i<$strLen-1; $i++){
         $newStr .="*";
    }
        $newStr = $newStr.$suffix;
        return $newStr;
 }


usage:
$input = "35468452";
$output =  hideLeft($input,'2');
//output will be *****52