Wednesday 29 October 2014

Show First 3/n Words From A String Value In PHP

Below code will explain how to do this in detail.

<?php

function showStripString ($num,$myString,$maxNumOfWords) {
    if($num>0) {
        if($num<=$maxNumOfWords) {
            $spaceChar = '/\S*';
            for($i=1;$i<$num;$i++) {
                $spaceChar .= '\s\S*';
            }
            $spaceChar .='/';
            preg_match("$spaceChar", $myString, $result);
            return $result[0];
        }else return "ERROR !!! Number of words exceeded the actaul number of words in you string ($myString)";
    }   
    else return "ERROR !!";
   
}
//your string
$str = "i want to buy a new car";
//Number of words you want to show
$number=3;

//remove whitespace from beginning and end of string
$str = trim($str);
//get number of whitespace
$nuberOfWhiteSpace = substr_count($str, ' ');
//Get Total number of words
$TotalNumberOfWords = $nuberOfWhiteSpace + 1;

//call function
echo showStripString(intval($number),$str,$TotalNumberOfWords);

?>

Wednesday 30 July 2014

Font with Icons (Font-Awesome)



Hai Developers, here I introduce a website for Awesome Font. They provide lot of icons in their font elements. So we need not add images for icons, just use their fonts. It is very easy and simple. So our web page will load very fast. Please check the below link.


 

WAMP Server Offline Error


One day, when I was run my WAMP server, it goes to offline. I checked is there any applications (Skype, Antivirus etc.) are running simultaneously. Everything was okay, but WAMP still shows offline. Finally I found the reason. It is because of; I changed my local IP address previous day, which is also used in apache config file for LAN WAMP connection. I commented the line as shown below in apache httpd.conf file.

#Listen 192.168.1.22:8081 

After that I restarted my WAMP server and it goes to online. :)

Thursday 15 May 2014

Solve: The Program Can't Start Because MSVCR100.dll is missing from your computer

When I was installing WAMP server on my formatted PC, I get this error.This issue because of, I didn't install any Microsoft Visual C++. The MSVCR100.dll file is part of the Microsoft Visual C++. You need to install this dll.

 For Windows 32 bit OS:

Microsoft Visual C++ 2008 SP1 Redistributable Package (x86)

Microsoft Visual C++ 2010 SP1 Redistributable Package (x86)

 

 For Windows 64 bit OS:
 
Microsoft Visual C++ 2008 Redistributable Package (x64)

Microsoft Visual C++ 2010 SP1 Redistributable Package (x64)



 For Windows 8:

Check this link Click  

Tuesday 18 March 2014

Pass Values Using Anchor Tag

Methode: 1


<a href="urlink.php?myvalueone=1&myvaluetwo=2">Pass Values</a>


In urlink.php

<?php   

    echo $_REQUEST["myvalueone"];
    // OR
    echo $_GET["myvalueone"];

    //AND

    echo $_REQUEST["myvaluetwo"];
    //OR
    echo $_GET["myvaluetwo"];

    //Process your actions here
   
?>

Result: 1122



Methode: 2

 

<form action="urlink.php" method="POST">

<input type="hidden" name="myvalueone" value="1" />
<input type="hidden" name="myvaluetwo" value="2" />

<a href="#" onclick="this.parentNode.submit()">Pass Values</a>

</form>


In urlink.php

<?php
       
    echo $_REQUEST["myvalueone"];
    // OR
    echo $_POST["myvalueone"];

    //AND

    echo $_REQUEST["myvaluetwo"];
    //OR
    echo $_POST["myvaluetwo"];
   
    //Process your actions here

?>

Result: 1122



Methode: 3


<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>

<a href="#NOD" rel="2" id="myvalues">Pass Value</a>

<script type="text/javascript">

    $(document).ready(function() {
        $('#myvalues').click(function() {
            $.ajax({
                type: "POST",
                url: "urlink.php",
                data:  {'myvalue' : $(this).attr('rel')},
                success: function(data) {
                alert(data);
                }
            });
    });
    });

</script>


In urlink.php

 
<?php
    //Process your actions here
    echo $_POST['myvalue'];
?>

Result:Javascript alert, popup with value 2

Monday 3 February 2014

Wamp Error: cannot execute menu item internal error

When I install wamp server on my friend's PC I got error like "Could not execute menu item (internal error)[Exception]".I goggled with this error and got solution.


Solution:1

please make sure none of following services is running on your system.
IIS, Skype, Zone Alarm, NOD32, Eset, Internet Optimizer, Google Accelerator, any other database server, any other webserver?
If you using any of the above application close it and select “restart all services” from WAMP menu.


Solution: 2

By default , the WAMP server will take 80 as its working port.You can change that port number as you like ... here are the steps to do that:
  •     click on WAMP server tray icon
  •     click on apache
  •     select http.conf(Here notepad will open ...).
    Scroll down and you will see the port number that WAMP server takes, change that port number to:

                                                     #Listen 12.34.56.78:80
                                                      Listen 80
    
                                                                      TO

                                                     #Listen 12.34.56.78:80
                                                      Listen 8080


    Save that file and restart the services. It will work fine. Now check by typing http://localhost:8080/.

Tuesday 28 January 2014

Custom AJAX File Uploader

I am very happy to share custom AJAX file up loader. It is very simple and using basic codes. So you can easily understand my code.

How to integrate this code ?


1. First you create index file, index.php


<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<form id="myUploadForm" name="myUploadForm" action="" method="post" enctype="multipart/form-data">
<input type="file" name="file[]" id="fileUpload" multiple="multiple" />
<input type="hidden" name="uploadedFilename" id="uploadedFilename" value="" />
</form>
<ul id="filelist">

</ul>
<script type="text/javascript">
$(function() {

    $(".removeUploadedFile").live('click',function() {
        var sel = $(this);
        if(!confirm("Do you want to remove this file ?")) return false;
        $.post('request.php',{action: 'remove', file: sel.attr('rel')}, function(data){
            if(data>0) {
                sel.closest('li').remove();
            }
        });
    });


    $("#fileUpload").change(function (e) {
            var sel = $(this);
            $.map($('#fileUpload').get(0).files, function(file) {
                $("#uploadedFilename").val(file.name);
                     e.preventDefault();
                    var formData = new FormData(sel.parents('form')[0]);
           
                    $.ajax({
                        url: 'request.php',
                        type: 'POST',
                        xhr: function() {
                            var myXhr = $.ajaxSettings.xhr();
                            return myXhr;
                        },
                        success: function (data) {
                            $("#filelist").append(data);
                            $("#fileUpload").val('');
                        },
                        data: formData,
                        cache: false,
                        contentType: false,
                        processData: false
                    });
                    return false;
            }); 
     });
});
</script>


2. Create another file request.php for AJAX call, request.php


<?php

switch ($_REQUEST['action']) {

        case 'upload':
        $targetPath = "uploads/";
        for($i=0; $i<count($_FILES['file']['name']); $i++){
               
                $tempFile =   $_FILES['file']['name'][$i];
                if($tempFile == $_REQUEST['uploadedFilename']){
                    //$targetFile =  str_replace('//','/', $targetPath) . $newFileName;
                    $cpy=0;
                    do {
                       
                        if($cpy>0)
                        $fileName="Copy".$cpy.$tempFile;
                        else $fileName=$tempFile;
                        $targetFile =  str_replace('//','/',$targetPath) .$fileName;
                        $cpy++;
                    }while(is_file($targetFile));
                       
                    if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $targetFile)) {
                        echo "<li>".$fileName."&nbsp;&nbsp;<a href='#NOD' class='removeUploadedFile' rel='".$fileName."'>Remove</a><input type='hidden' name='hdnAttach[]' value='".$fileName."' ></li>";
                    } else{
                        echo "<li>There was an error uploading the file(".$fileName."), please try again! </li>";
                    }
                   
                }
               
        }
        break;
       
        case 'remove':
            if(file_exists("uploads/".$_POST['file'])) {
                unlink("uploads/".$_POST['file']);
                    echo 1;
                }
        break;

}

?>

3. Create a folder 'uploads' for upload image.The uploaded image should be stored in this folder.

 

 

Root Path :



Monday 13 January 2014

Simple file uploader (Php File Uploader)


I found a website phpfileuploader.com, they provide simple code for file uploading.We can upload multiple files also.I used plupuploader for file uploading before. When I checked their code, I moved this uploading techniques.

It is very simple,easy to understand and easy to integrate. They provide demo development code and we can start the development with this code.

Monday 6 January 2014

HTC Desire C shows error like no images and videos available

My phone is HTC Desire C.Two days ago I couldn't open my gallery.When I try to open gallery It shows error like no images and videos available.I thought it is because of virus.I restarted my mobile, removed my SD/memory card. But the result is still same.

I googled this error and finally I found a link.

From the above link instruction I went to setting>>Apps>>Running.

I couldn't find out the mediascanner service, I realized that It was my mistake, because suddenly I closed media services using task manager.It killed my media services.

Then I changed the setting like setting>>Apps>>All>>Media

I opened the above root, I found that media app is disabled. I enable its services and solved my problem.

Thursday 2 January 2014

Create MYSQL Table From CSV File Using PHP

The below example shows how to create MYSQL table from CSV file using PHP code.
For reference: Click Here

<?php

 //table Name
$tableName = "MyTable";
//database name
$dbName = "MyDatabase";


 $conn = mysql_connect("localhost", "root", "") or die(mysql_error());
 mysql_select_db($dbName) or die(mysql_error());

//get the first row fields
$fields = "";
$fieldsInsert = "";
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    if(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $fieldsInsert .= '(';
        for ($c=0; $c < $num; $c++) {
            $fieldsInsert .=($c==0) ? '' : ', ';
            $fieldsInsert .="`".$data[$c]."`";
            $fields .="`".$data[$c]."` varchar(500) DEFAULT NULL,";
        }
       
        $fieldsInsert .= ')';
    }
   

    //drop table if exist
    if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$tableName."'"))>=1) {
      mysql_query('DROP TABLE IF EXISTS `'.$tableName.'`') or die(mysql_error());
    }
   
    //create table
    $sql = "CREATE TABLE `".$tableName."` (
              `".$tableName."Id` int(100) unsigned NOT NULL AUTO_INCREMENT,
              ".$fields."
              PRIMARY KEY (`".$tableName."Id`)
            ) ";
   
    $retval = mysql_query( $sql, $conn );
   
    if(! $retval )
    {
      die('Could not create table: ' . mysql_error());
    }
    else {
        while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
           
                $num = count($data);
                $fieldsInsertvalues="";
                //get field values of each row
                for ($c=0; $c < $num; $c++) {
                    $fieldsInsertvalues .=($c==0) ? '(' : ', ';
                    $fieldsInsertvalues .="'".$data[$c]."'";
                }
                $fieldsInsertvalues .= ')';
                //insert the values to table
                $sql = "INSERT INTO ".$tableName." ".$fieldsInsert."  VALUES  ".$fieldsInsertvalues;
                mysql_query($sql,$conn);   
        }
        echo 'Table Created';   
    }
   
    fclose($handle);
       
}


?>

If you have any questions, please post it as comments.

Wednesday 1 January 2014

Create XML file and add/cascade css using php

The below example shows how to create a XML file using php and also shows how to add css on it.Here we are using "simplexml" php function. For more details, click here.

create a php file (index.php) and copy & past the below code

################### Start PHP Code #####################

<?php


class SimpleXMLElement_Plus extends SimpleXMLElement {

    public function addMyCss( $name, $value )
    {
        $dom_sxe = dom_import_simplexml($this);      
        $dom_parent = $dom_sxe->ownerDocument;      
        $xpath = new DOMXPath($dom_parent);
        $first_element = $xpath->evaluate('/*[1]')->item(0);
        $pi = $dom_parent->createProcessingInstruction($name, $value);
        $dom_parent->insertBefore($pi, $first_element);
    }
}


$xml = new SimpleXMLElement_Plus('<xml/>');
$xml->addMyCss('xml-stylesheet', 'type="text/css" href="cd_catalog.css"');
$track = $xml->addChild('markers');
for ($i = 1; $i <= 8; ++$i) {
    $marker = $xml->addChild('marker');
    $marker->addChild('name', "name$i");
    $marker->addChild('address', "address $i");
    $marker->addChild('lat', "lat $i");
    $marker->addChild('lng', "lng $i");
}

Header('Content-type: text/xml');
print($xml->asXML());

?>

################### End PHP Code #####################


Create a CSS file(cd_catalog.css) and copy and past the below code.


######################### Start CSS  ##################

markers
{
margin:10px;
background-color:#ccff00;
font-family:verdana,helvetica,sans-serif;
}

name
{
display:block;
font-weight:bold;
}

address, lat, lng
{
display:block;
color:#636363;
font-size:small;
font-style:italic;
}

########################## End CSS  ##################

If you have any questions, please post it as comments.