Export to excel in php with jquery/Javascript

Export to excel in php with jquery/Javascript

In this article,I will explain how to export excel file in php with JQuery.we are going to export an HTML table to a MS Excel document as it is displayed on the HTML page.it is very easy to export PHP HTML data to excel in PHP.please check following Export to excel example.

Example:Export to excel in php

File:php_export_to_excel.php
<?php
if(isset($_REQUEST['csvdata']))
{
////download to excel
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=csv_excel.xls');
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['csvdata'];
exit();
}
?>
<html>
<head>
<script>
function getCsvData()
{
$("#csvdata").val($("<span>").append ($("#customers").eq(0).clone()).html());
return true;
}
</script>
<title>Export to excel in php with Jquery</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<html>
<head>
<style type="text/css">
#customers
{
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
width:50%;
border-collapse:collapse;
}
#customers td, #customers th
{
font-size:1em;
border:1px solid  #999999;
padding:3px 7px 2px 7px;
}
#customers th
{
font-size:1.1em;
text-align:left;
padding-top:5px;
padding-bottom:4px;
background-color: #666666;
color:#ffffff;
}
#customers tr.alt td
{
color:#000000;
background-color: #CCCCCC;
}
</style>
</head>
<body>
<form method="post" onSubmit="javascript:return getCsvData()">
<table align="center" id="customers">
<tr>
  <th>Company</th>
  <th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr class="alt">
<td>Berglunds snabbköp</td>
<td>Sweden</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Mexico</td>
</tr>
<tr class="alt">
<td>Ernst Handel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
<tr class="alt">
<td> Essen</td>
<td>Germany</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Canada</td>
</tr>
<tr class="alt">
<td>Magazzini</td>
<td>Italy</td>
</tr>
<tr>
<td>North/South</td>
<td>UK</td>
</tr>
<tr class="alt">
<td>ABC</td>
<td>France</td>
</tr>
</table>
<table align="center" id="customers1">
<tr> 
      <td  colspan="6"align="center"><input type="hidden" id="csvdata" name="csvdata"> 
        <input type="submit" value="Export to Excel"> </td> 
    </tr> 
</table>
</form>
</body>
</html>


Bookmark and Share

Find textbox length in javascript

Find textbox length in javascript

In this tutorial,I will explain how to find the length of textbox using javascript.It is very easy to find textbox length in javascript.we can use javascript length property.

Example:Find textbox length in javascript
<html>
<head>
<title>Textbox limit characters</title>
<script>
function findTextboxLength()
{
textbox_val=textbox1.value;//gets the value of the input element entered by the user.
    textbox_length = textbox_val.length;//find the length of textbox in javascript
    if (textbox_length < 10)
    {
        char = 10 - textbox_length;
        msg = char + " characters left";
        text_span.innerHTML="<font color=blue>" + msg + "</font>";
    }
    else
    {
        text_span.innerHTML="<font color=red>Message is too long</font>";
    }
 }
</script>
</head>
<INPUT type="text" id="textbox1" onKeyUp="findTextboxLength();" >
<span id="text_span" name="text_span"></span>
</html>


Bookmark and Share

Javascript Find Vowels in a String

Javascript Find Vowels in a String
In this article, I will explain how to find Vowels in a String and how to find total number of vowels in a string in JavaScript. I have written simple script for checking vowels in a string in JavaScript. I have used regular expression. For me, a regular expression is best.


Read more "Find Vowels in a String in Javascript"


Bookmark and Share

JQuery change to uppercase

JQuery change to uppercase

Change text to UpperCase using jQuery.In this article,I will explain How to Change text to UpperCase using jQuery.We are using following JavaScript code to Change text to UpperCase
using jQuery.
The keyup() method is used to Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element and The toUpperCase() method converts a string to uppercase letters.

You can use javascript toUpperCase() method to Change text to UpperCase 
using jQuery.In the following code we have called the  keyup event in the JavaScript to
Change lowercase chars to uppercase. This function would be called when any
user enters char on the textbox .The javascript code below shows how to Change text to UpperCase using jQuery.


Bookmark and Share

My SQL get string length

My SQL get string length

Get the length of string in my sql server.In this article,I will  explain how to get the length of string in My SQL server.

My SQL string LENGTH  function Returns the length of the character string.
Syntax: LENGTH(string)


Query to get string Length in My SQL
select LENGTH('str') as str_length;

I hope above query will help you to get the length of the character string in My SQL server.


Bookmark and Share

MS SQL get string length

MS SQL get string length

Get the length of string in ms sql server.In this article,I will  explain how to get the length of string in MS SQL server.

MS SQL string LEN  function Returns the length of the character string.
Syntax: LEN(string)


Query to get string Length in MS SQL
select LEN('str') as str_length;

I hope above query will help you to get the length of the character string in MS SQL server.


Bookmark and Share

Jquery spell checker (Textarea spellcheck jquery)

Jquery spell checker

In this article, I will explain about jquery spell checker.We are using following jquery code to check spell in Jquery.This plugin is used to check an area of text within an HTML document.The
plugin comes with an example PHP script that supports two type of spell checking engines:


Bookmark and Share

Javascript set focus on a table cell

Javascript set focus on a table cell

How to set focus to table cell using javascript.In this article,I will explain how to set focus to table cell using javascript.We are using following JavaScript code to set focus on the Table row's cell.The focus() method is used to give focus to an element.

You can use javascript focus() method to set focus on element,set focus on input/textbox.In the following code we have created the function setFocus() in the JavaScript to show the use of "focus()" method. This function would be called when any user clicks on the link "Set Focus to Table Cell".
The javascript code below shows how to set the focus on an element/input field (textbox).


Bookmark and Share

JQuery for each Loop example

JQuery for each Loop example

jQuery.each() function. 
In this article,I will explain How to use JQuery for each Loop with example.The jQuery library provides a jQuery .each() method, which will loop through each  matched element.
The jQuery .each() function is used to loop through each matched element.

Syntax:
.each(function(index,Element))


Bookmark and Share

Javascript get url parameters

Javascript get url parameters.

In this article, I will explain  how to get url parameters in javascript.We are using following JavaScript code to get url parameters using javascript.I have written simple javascript function which will get a URL parameter and return it to you.
Suppose,My URL is http://example.com/pagename.html?a=1&b=2 and i want to
get parameters a=1,b=2
please check following code to Retrieve URL GET parameters with Javascript.


Bookmark and Share

Javascript get url page name

Javascript get url page name.

In this article, I will explain  how to get page name from url in javascript.We are using following JavaScript code to get url page name using javascript.The filename is the last part of the URL from the last trailing slash ('/').
Suppose,My URL is http://example.com/pagename.html and i want to get page name pagename.html


Bookmark and Share

Javascript change text to uppercase

Javascript change to uppercase

Change text to UpperCase using Javascript
Suppose, I want to convert lowercase chars to uppercase as the user types using Javascript. In this article,I will explain How to Change text to UpperCase using Javascript.We are using following JavaScript code to Change text to UpperCase using Javascript.

The keyup() method is used to Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element and The toUpperCase() method converts a string to uppercase letters.


Bookmark and Share

Avoid jQuery conflict with Other JavaScript library(prototype,YUI,mootools)

Avoid jQuery conflict with Other JavaScript library(prototype,YUI,mootools)

In this jQuery article, I will explain how to avoid jquery conflict with other javascript libraries.
javascript libraries such as YUI, prototype conflict with Jquery library as prototype library also uses `$` sign.To resolve this issue, jQuery has .noConflict() method.

.noConflict() method: Relinquish jQuery's control of the $ variable (override the $ function)
we can avoid prototype and jquery conflict using .noConflict() method.


Bookmark and Share

Insert dynamic row in table using jquery

Insert dynamic row in table using jquery

In this tutorial,I will show how to insert dynamic row in table using jquery.
dynamically add row in table using jquery is very simple as jQuery provides clone() function to clone HTML elements. Using this function we can clone a row and add this row to table using insertBefore() function.

For adding dynamic row in table, we have used insertRow() and clone() method.


Bookmark and Share

Remove last character of string in jquery/javascript

Remove last character of string in jquery/javascript.
In this tutorial, I will explain how to remove last character of a string in javascript.To remove the last character of a string can be easily done by javascript functions

Example:How to delete last character from a string using javascript/jQuery?
<script language="javascript" type="text/javascript">
var string = 'Hello!';
var new_string = string.substring(0, string.length-1);//This will only removes the last character
alert(new_string);
</script>


Bookmark and Share

Javascript get windows username

Javascript get windows username.
In this tutorial,I will explain how to get windows username using javascript.

Example1:Retrieve Windows Username with JavaScript Scripting
<html>
<head>
    <script language="javascript">
        function GetWindowsUserName()
        {
            var win = new ActiveXObject("WScript.Shell");
            var username=(win.ExpandEnvironmentStrings("%USERNAME%"));
alert(username);
        }
    </script>
</head>
<body OnLoad="GetWindowsUserName();">
</body>
</html>


Bookmark and Share

Javascript print this page,window,Div,Dialogue box

Javascript print this page,window,Div,Dialogue box

In this tutorial, I will explain how to print window using javascript.We are using JavaScript window.print() function to print a window of this page,print dialogue box,print div.One of the most basic JavaScript commands is document.write. This simply prints the specified text to the page.JavaScript programs cannot directly access printers.you need to generate the printable data in a separate browser window.
Example:How do I print JavaScript output?

Javascript print using Hyperlink:-
<a href= "javascript:window.print();"> Print</a>  


Javascript print Button:-
//You can call the JavaScript print function .This will automatically open the print dialogue box for the user.
<input type="button" value="Print" onclick="window.print();"> 


Bookmark and Share

Difference between curl and file_get_contents

Difference between curl and file_get_contents


In this tutorial,I will explain difference between curl and file_get_contents.
PHP offers two main options to get a remote file, curl and file_get_contents. There are many difference between the two.
file_get_contents - It is a function to get the contents of a file
curl - It is a library.curl supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading HTTP form based upload, proxies, cookies.
file_get_contents() for a remote file, it is very slow, and does not handle redirects, caching, cookies.
Curl is a much faster alternative to file_get_contents.


Bookmark and Share

Format phone number in ms sql server?

Format phone number in ms sql server?

In this tutorial, I will explain how to format phone number in ms sql server.

Mysql Phone Number Format is useful when you want to return the phone number in specific format.
sometime we need to format the phone number before displaying them in website.Suppose, we have to format phone number in [(000) 000-0000] format.


Bookmark and Share

Restrict special characters being entered in textbox using jquery/javascript?

Restrict special characters being entered in textbox using jquery/javascript?

In this tutorial,I will explain how to restrict the special characters being entered in textbox using jquery/javascript.
It is very important to check user input text validity to prevent the sql injection that can harm your database.


Bookmark and Share

javascript padding/convert number to string with leading zeros

Javascript padding/convert number to string with leading zeros

In this tutorial,I will explain how to padding/convert number to a string with leading zeros.
padding in javascript is very easy.we are using javascript to format number with leading zero.

Example:Javascript format number with leading zero
<script language="javascript" type="text/javascript">
var number=10;
var num=Number(number);
num_to_string=num.toString();
if(num_to_string.length==1)
{
num_to_string=0+num_to_string;
}
alert(num_to_string);
</script>


Bookmark and Share

Javascript:Disable Back Button in Browser (firefox,IE,..)

Javascript:Disable Back Button in Browser.

Disable Back Button in Browser(IE,firefox,Google Chrome, Opera, Safari, Internet Explorer) using javascript.
In this tutorial, I will explain how to disable the back button on FireFox's/IE browser.
this code will works for all web browsers such as Google Chrome, Opera, Safari, Internet Explorer etc.
Please check two methods to somewhat disable a browser's Back button.
<script language="javascript" type="text/javascript">
window.history.forward(1);
</script>


Bookmark and Share

jquery trim spaces - jQuery $.trim method

jquery trim spaces - jQuery $.trim method

In this tutorial, I will explain how to removes the two whitespaces at the start and at the end of the string.
Removes the two whitespaces at the start and at the end of the string.
<html>
<title>jquery trim spaces</title>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
  $(document).ready(function(){
    
    $("span").click(function () {
      var str = "     jquery trim spaces     ";
      str1 = jQuery.trim(str);
      alert(str1);
    str2 = $.trim(str);//using the jQuery $.trim method
      alert(str2);
     });
  });
  </script>
</head>
<body>
  <span>jquery trim spaces</span>
</body>
</html>


I hope this tutorial will help you to remove whitespaces at the start and at the end of the string.


Bookmark and Share

JQuery-Remove all spaces from string using javascript/JQuery/Regular expressions.

Remove all spaces from string using javascript/JQuery/Regular expressions.

In this tutorial, I will explain how to remove all spaces in a string using jquery,
remove all occurences of a character from a string.
I need to remove spaces in the string.I will use JQuery/Regular expressions/javascript to replace spaces from string.
You can replace string with '_','-'....etc.
Removing extra space from the string using javascript and Regular expression is very easy.
<script type="text/javascript">
function removeSpaces(str)
{
var s=str.replace(/\s/g, "");
return s;
}
var new_str=removeSpaces('jquery remove space from string using javascript');
</script>


Bookmark and Share

jquery onclick change class script (.removeClass() and .addClass())

JQuery onclick change class (.removeClass() and .addClass())

In this example,I will show How to change class name using Jquery .removeClass() and .addClass() property.

Syntax:
.removeClass(className)
className will be One or more classes to be removed from the class attribute of each matched element.


Bookmark and Share

Strict Standards jcache error - Joomla

Strict Standards jcache error - Joomla

Strict Standards: Accessing static property JCache::$_handle - Joomla error

How about fixing the error?
1. Open cache.php (line number 419)and change all occurences of $this->_handler to JCache::$_handler:

<?php
   public function &_getStorage()
   {
      if (!isset(JCache::$_handler)) {
         JCache::$_handler = JCacheStorage::getInstance($this->_options['storage'], $this->_options);
      }
      return JCache::$_handler;
   }
   ?>


Bookmark and Share

Currency Conversion using PHP Script-Currency Converter Example

Currency Conversion using PHP Script,curl,Ajax,Jquery,Javascript-Currency Converter Example

In this article, I will explain how to convert Currency using PHP,curl,Ajax,Jquery.
Calculate live currency and foreign exchange rates with this free currency converter script.This Free Currency Exchange Rates Calculator helps you convert any amount from one currency to another.

Currency converter for top world currencies.Convert more than 250 foreign currency cross rates at today's exchange rate.You can easily convert between currencies with PHP,Ajax,Curl,JQuery Script using the Google Calculator API. This tutorial explain how to create a php Application to convert between any currency and a form to allow user submission.

I was looking for a way to convert any amount from one currency to another on a website. The user would enter some amount like '100' and select INR as the currency, and then chooses USD dollars as the currency to convert to. I'd like to convert that amount automatically, through some API, and show him the amount in the currency he chose to convert to. and now i have Currency Conversion php API. which will convert between any currency.


Bookmark and Share

Difference between unsigned short int and long int?

Difference between unsigned short int and long int?
  • An unsigned integer is either positive or zero.
  • An unsigned integer containing n bits can have a value between 0 and 2 n - 1
  • You can write a number between 0 and 10 n - 1. 
  • unsigned short integers: (16 bits)
  • unsigned long integers (32 bits) 
  • unsigned Short integers can be used to store numbers between 0 and 2 16 - 1, or 65,535.
  • unsigned  Long integers can be used to store numbers between 0 and 2 32 - 1, or 4,294,967,295.
  • and unsigned double integers can be used to store numbers between 0 and 2 64 - 1, or 18,446,744,073,709,551,615.


Bookmark and Share

Regular expression find String,Word,Numbers in String

Regular expression find string,word,numbers in string.
In this section,I will explain how to find words,string,numbers in string using Regular expression.
It is very easy to match strings or patterns of characters in php using regular expresions.
A regular expression provides a matching strings of word,particular characters, numbers,or patterns of characters.Abbreviations for `regular expression` includes `regex` and `regexp`

Example 1:
//Regular expression find word in string
 In first example, we are using Regular expression to fing word in string using `\b`.
`\b` allows you to find a perticular word only using a regular expression in the form of \bword\b.
<?php
$name = 'I have 6 years of exprience';
preg_match( '/\byears\b/', $name, $match );
echo $match[0];
?>
Output: years


Bookmark and Share

wait_timeout Mysql | max_connections Mysql

wait_timeout Mysql :

wait_timeout defines the number of seconds a mysql thread waits in idle state before mysql kills it.

MySQL uses a lot of different timeout variables at different stages.when connection is just being established connect_timeout is used. When server waits for another query to be sent to it wait_timeout.
By default, the server closes the connection after eight hours if nothing has happened.
You can change the time limit by setting the wait_timeout variable when you
start mysqld.


Bookmark and Share

Clustered indexes Vs Non-clustered indexes-MySql

Clustered indexes Vs Non-clustered indexes-MySql
  • Clustered index will physically order the data based on the values in the index.
  • A non clustered index is a special type of index that stores the records in logical order rather than physical order. This means, a table can have many non clustered indexes. More non clustered indexes per table means more time it takes to write new records.
  • A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.
  • A non clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a non clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.
  • Clustered index is physically stored a table can have 1 clustered index.
  • Non clustered index is logically stored a table can have 249 non  clustered  index.


Bookmark and Share

Difference between Primary Key and Unique key?

Difference between Primary Key and Unique key?

Primary Key:
1.Primary Key doesn’t allow NULLs values.
2.There will be only one primary key in a table.
3.Clustered index is created in Primary key.
4.Primary key allows each row in a table to be uniquely identified and ensures that no duplicate rows exist.


Bookmark and Share

Generate unique ID in PHP

PHP UniqueID:
Generate unique ID in PHP
A unique ID can be created in PHP using the uniqid () function.

uniqid():Returns the unique identifier, as a string.
Here are some examples:

<?php 
 //creates a unique id with the 'unique' prefix
 $a = uniqid('unique');
 echo $a;
 echo "<br>";
 //creates a longer unique id with the 'unique' prefix
 $b = uniqid ('unique', true);
echo $b;
 echo "<br>";
 //creates a unique ID with a random number as a prefix
 $c = uniqid (rand (),true);
 echo $c;
 echo "<br>";
 //this md5 encrypts the username from above
 $md5c = md5($c);
 echo $md5c;
 ?> 


Bookmark and Share

Remove duplicate values from an array php

How can remove duplicate values from an array php

array_unique :Removes duplicate values from an array

Syntax:
array_unique(array,sort flag);
sort flag:
ORT_REGULAR - compare items normally
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale.

Example:
<?php
$arr = array("php","tutorial","php","example");
 $unique_arr = array_unique($arr); //removes duplicate values from an array
print_r($unique_arr ); 
?> 
Outputs:
Array
(
[0] => php
[1] => tutorial
[2] => example
)


Bookmark and Share

Redirect php web page using PHP header loaction redirect script.-php redirection

Redirect php page To Another web page URL using PHP header loaction redirect script-php redirection

You can easily redirect php page to the different web page using PHP header() function

the following PHP script redirect the user to rajeshstutorials.blogspot.com
<?php
header( 'Location: http://rajeshstutorials.blogspot.com/' ) ;
?>


Bookmark and Share

Auto refresh webpage every 5 second with PHP,HTML and JavaScript:

Auto refresh webpage every 5 second with PHP,HTML and JavaScript: 
In this section,I will show how to auto refresh web page with php,HTML and Javascript

Auto refresh the web page every 5 seconds, with PHP
<?php
$url=$_SERVER['REQUEST_URI'];
header("Refresh: 5; URL=$url"); 
?>

Using HTML Meta Tag:
Refresh Page after every 5 seconds.
<meta http-equiv=”refresh” content=”5; URL=http://rajeshstutorials.blogspot.com”>

Using Javascript:
<body onload=”javascript:setTimeout(“location.reload(true);”,5000);”>

time in milliseconds. So if you want to refresh web page after every 5 second than time will be 5000.


Bookmark and Share

Different types of errors in PHP?


Different types of errors in PHP?

Three are three types of errors:

1. Notices: These are trivial,non-critical errors that PHP encounters while executing a script.
 for example, accessing a variable that has not yet been defined. By default,
such errors are not displayed to the user at all .

2. Warnings: These are more serious errors – for example, attempting
to include() a file which does not exist. By default, these errors are
displayed to the user, but they do not result in script termination.

3. Fatal errors: These are critical errors – for example,
instantiating an object of a non-existent class, or calling a
non-existent function. These errors cause the immediate termination of
the script, and PHP’s default behavior is to display them to the user
when they take place.


Bookmark and Share

what is the difference between =,==,===?

what is the difference between =,==,===?

= assigns a value, == checks if value is the same, === checks if value is the same and the variables are of the exact same type.


Bookmark and Share

What is the maximum length of a URL?

What is the maximum length of a URL?

Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL

If you are using the GET method, you are limited to a maximum of 2,048 characters, minus the number of characters in the actual path.
However, the POST method is not limited by the size of the URL for submitting name/value pairs.

Maximum length depends on browsers.Firefox, Safari , Opera  supports more than 100,000 characters.  but some times server like Apache, IIS may not support these longer URL’s. so better to keep it short URL.


Bookmark and Share

Javascript Interview Questions and Answers For Freshers/Experienced Candidates

Javascript Interview Questions and Answers


In this section, I have selected advanced javascript interview questions and answers for Freshers/Experienced Candidates.Last few months I have been working to select best question and answer set for JavaScript interview questions.I have written some  JavaScript  tutorials.

What are JavaScript types? 
Number, String, Boolean, Function, Object, Null, Undefined.

How do you convert numbers between different bases in JavaScript?
Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);

What does "1"+2+3 evaluate to?
Since 1 is a string, everything is a string, so the result is 123.

How about 3+5+"8"?
Since 3 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 88 is the result.


Bookmark and Share

print_r() Versus var_dump()

Difference between print_r() and var_dump(): 
In this article, I will explain difference between print_r(), var_dump() and var_export().

var_dump():
The var_dump function displays structured information about variables/expressions that includes its type and value

Syntax
var_dump(variable1, variabl2, ....)

Example:
<?php
$str = array(1, 2, "a");
var_dump($str);
?>
OUTPUT:
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
string(1) "a"
}


Bookmark and Share

PHP Radio button array example

PHP Radio button array example
In this article,I will explain how to use Radio buttons in php.


Example:
<?php
if(isset($_POST['Submit'])){
$radioValue = $_POST['radio'];
}
?>
<HTML>
<HEAD>
    <TITLE> PHP Radio button array example </TITLE>
 </HEAD>
<BODY>
     <TABLE id="table_Id"  border="1">
        <TR>
            <TD><input type="radio" name="radio" value="1"/></td>
            <TD><input type="radio" name="radio" value="2"/></td>
             <TD><input type="radio" name="radio" value="3"/></td>
           <TD><input type="radio" name="radio" value="4"/></td>
           </TR>
<TR><td colspan=4 align=center><INPUT type="submit" value="Submit"> </td> </TR>
    </TABLE>
 /BODY>
</HTML>


Bookmark and Share

What is the output from this PHP code?

What is the output from this PHP code?
$valid = TRUE;
$cnt = 0;
while ($valid = TRUE) {
$cnt++;
if ($cnt > 10) { $valid = FALSE; }
}
echo "$cnt";

Answer: infinite loops will run forever


Bookmark and Share

Walk-In: PHP Developers in Bangalore:4D Technologies

Walk-In: PHP Developers in Bangalore

Company Profile:
4D Technologies Pvt. Ltd.
www.unibrostechnologies.com

Job Description :
Candidate Should be available for the interview (Face to face interview) on Friday (10th February 2012) any time between 10 AM to 4 PM.
Skills :
For Experienced Candidates : The candidates should have good hands-on Experience in PHP & Sugar CRM. (Exposure to RIA is a plus)
For Freshers : The candidates should be well versed in PHP. Later the client will train them on sugar CRM.


Bookmark and Share

Fatal error: Call to undefined function mcrypt_get_iv_size()

Fatal error: Call to undefined function mcrypt_get_iv_size()
In this tutorials,I will show how to resolve Fatal error: Call to undefined function mcrypt_get_iv_size()

Steps:


1.Download libmcrypt.dll from
   http://ftp.emini.dk/pub/php/win32/mcrypt/

2.Copy the file to system32.

3.Open valid php.ini file in the windows directory

4.Search for a line
;extension=php_mcrypt.dll
in php.ini file

5.Remove the ; at the beginning of the line.

6.Rrestart apache.

7.Done



Bookmark and Share

Enable Htaccess in localhost AppServ

Enable Htaccess in localhost AppServ.
In this tutorials,I will show how to enable htaccess in localhost AppServ

1) Open AppSer installed folder
      For Example In Windows:
      D:\AppServ\Apache2.2\conf\
        OR
      C:\AppServ\Apache2.2\conf\

2).Find and open httpd.conf file

3).Search below line
      #LoadModule rewrite_module modules/mod_rewrite.so

4).if hash is there remove that hash("#")sign in front, becomes:
  LoadModule rewrite_module modules/mod_rewrite.so.

5).save the file

6). restart the AppServe

7).Done.

Cheers..:)


Bookmark and Share

Zend PHP 5 Certification Syllabus

Zend PHP 5 Certification Syllabus 

Exam Topics
MVC
  •     Components
  •     Pattern Basics
  •     Bootstrap
  •     Zend_Controller
  •     Zend_Layout
Infrastructure
  •     Zend_Config
  •     Zend_Session
  •     Zend_Registry
  •     Zend_Loader
Internationalization
  •     Zend_Date
  •     Zend_Translate
  •     Zend_Locale
  •     Zend_Currency
  •     Zend_View_Helper_ Translate
  •     Internationalization Performance


Bookmark and Share

How to count non-empty cells in one row In MySQL


How to count non-empty cells in one row in MySql.
In this section, I will explain how to count non-empty cells in one row in MySql.

Suppose we have to count non empty cells of Price table.

Price table:
Col1          Col2        Col3
1000000     200           1000
4545556     400            NULL     

Query:
SELECT IF(col1 IS NOT NULL, 1, 0) + IF(col2 IS NOT NULL, 1, 0) + IF(col3 IS NOT NULL, 1, 0) AS total_price 
FROM price_table

This query will return Total price of non empty cells(col1,col2,col3)


Bookmark and Share

Import CSV/Excel data into MYSQL database via PHP Script;

Import CSV/Excel data into MYSQL database via PHP Script;

In this article,I will explain How to import the CSV/Excel file in to MYSQL database via PHP Mysql Script.we can use PHP fgetcsv() function to parse/import data from CSV/Excel file into Mysql Database.
fetchCsv.php file will upload the CSV/Excel file and imort the file into Mysql Database.
please check following code:
Example:


fetchCsv.php
<?php
if(isset($_POST["Import"]))
{
$host="localhost"; // Host name.
$db_user="root";
$db_password="";
$db='myDB'; // Database name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());

echo $filename=$_FILES["file"]["tmp_name"];
//echo $ext=substr($filename,strrpos($filename,"."),(strlen($filename)-strrpos($filename,".")));


 if($_FILES["file"]["size"] > 0)
 {

$file = fopen($filename, "r");
         while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
         {
            print_r($emapData);
            $sql = "INSERT into myTable(name,address,email,password) values('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
            mysql_query($sql);
         }
         fclose($file);
         echo "CSV File has been successfully Imported";
}
else
echo "Invalid File:Please Upload CSV File";

}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import CSV/Excel file</title>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<table border="1" width="40%" align="center">
<tr >
<td colspan="2" align="center"><strong>Import CSV/Excel file</strong></td>
</tr>

<tr>
<td align="center">CSV/Excel File:</td><td><input type="file" name="file" id="file"></td></tr>
<tr >
<td colspan="2" align="center"><input type="submit" name="Import" value="Import"></td>
</tr>
</table>
</form>
</body>
</html>

fetchCsv.php file will upload the CSV/Excel file and imort the file into Mysql Database.
If you face any problem than let me know via comment .


Bookmark and Share

PHP based companies in Pune list with address.

PHP based companies in Pune list with address.

List of IT & Software PHP based Companies in Pune, Maharastra, India.In this section, I have added some PHP based companies in Pune.

Cybage
http://www.cybage.com
Cybage Software Pvt. Ltd.
West Avenue, Kalyani Nagar,
Pune - 411006
Ph: 91-20-66041700
Fax: 91-20-66041701
-------------------------------------------------------------------------
Clarion Technologies
http://www.clariontechnologies.co.in
Fourth Floor, Tower S - 4,
Magarpatta City, Hadapsar,
Pune- 411028.
Tel: +91 20 66009500
-------------------------------------------------------------------------


Bookmark and Share

What is the output? int i=7 printf("%dn",i++*i++);


What is the output? int i=7 printf("%dn",i++*i++);

Answer: The answer is 56
The compiler will use right to left associtavity here and when it gets i++ then for the value of i, nothing happens then it gets *, it puts it in stack. then gets another i++ by this time the 1st ++ is executed


Bookmark and Share

what is the output of the program? int n=f,m; n==m++; m==++n; printf(n, m);.?

what is the output of the program?
int n=f,m;
 n==m++;
m==++n;
printf(n, m);.?

Ans: compilation error occurs


Bookmark and Share

Wipro written test question paper 2012 at Hyderabad

Wipro written test question paper 2012 at Hyderabad

1. Given the following statement enum day = { jan = 1 ,feb=4, april, may} What is the value of may?
(a) 4
(b) 5
(c) 6
(d) 11
(e) None of the above

2. Find the output for the following C program
main
{int x,j,k;
j=k=6;x=2;
x=j*k;
printf("%d", x);

3. Find the output for the following C program

fn f(x)
{ if(x<=0) > return;
else f(x-1)+x;
}

4. Find the output for the following C program

i=20,k=0;
for(j=1;j {k+=j<10?4:3;> }
printf("%d", k);

Ans. k=4

5. Find the output for the following C program

int i =10
main()
{int i =20,n;
for(n=0;n<=i;) > {int i=10;
i++;
}
printf("%d", i);

Ans. i=20

6. Find the output for the following C program

int x=5;
y= x&y

7.Find the output for the following C program

Y=10;
if( Y++>9 && Y++!=10 && Y++>10)
{printf("%d", Y);
else
printf("%d", Y);
}

Ans. 13

8. Find the output for the following C program

f=(x>y)?x:y

a) f points to max of x and y
b) f points to min of x and y
c)error

Ans. (a)

9. What is the sizeof(long int)

(a) 4 bytes
(b) 2 bytes
(c) compiler dependent
(d) 8 bytes

10. Which of the function operator cannot be over loaded

(a) <= > (b) ?:
(c) ==
(d) *


Bookmark and Share

What is the name given to the process of initializing a micro computer with its OS?

What is the name given to the process of initializing a micro computer with its OS?
  1. Cold booting
  2. Bbooting
  3. Warm booting
  4. Boot Recording


Bookmark and Share

Major expressions used with find command to select file is it has been accessed in more than 375 days

Wipro Technical interview Questions

Major expressions used with find command to select file is it has been accessed in more than 375 days,is  A)-a time +365 B) -m time +365 C)-a time -365 D) -m time -365 

Ans:C (-a time -365)


Bookmark and Share

Align text in text box using HTML


Align text in text box
In this article,I will explain how to align text in text box using TextBox TextAlign Property
There is a property called "style" which you have to set style="text-align:right"

Example:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Align text in text box</title>
</head>
<body>
<input style="text-align:center" type="text" name="Center Align" value="Center Align" />
<input style="text-align:left" type="text" name="Left Align" value="Left Align" />
<input style="text-align:right" type="text" name="Right Align"  value="Right Align"/>
</body>
</html>


Bookmark and Share

How to enable .htaccess in wamp server

How to enable .htaccess in wamp server
In this article,I will explain how to enable .htaccess in wamp server.


1Open wamp_server  (Go to Wamp -> Right click at icon in the taskbar=> Apache=> httpd.conf)



Bookmark and Share

How to get base url in PHP?

How to get base url in PHP?

Example:
<?php
$baseUrl = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? 'https://' : 'http://';
$baseUrl .= isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : getenv('HTTP_HOST');
echo $baseUrl .= isset($_SERVER['SCRIPT_NAME']) ? dirname($_SERVER['SCRIPT_NAME']) : dirname(getenv('SCRIPT_NAME'));
?>
Output:
http://domain.com/project/


Bookmark and Share

Create Password protected Zip file in PHP

Create Password protected Zip file in PHP.
In this article,I will explain how to create password protected zip file using php script.
First you will have to Install 7zip Software.

Example:
<?php
$path=$_SERVER['DOCUMENT_ROOT'];
$pwd = "123";
$zipfile = $path."test.zip";
$filearch = $path."test";
system("7za.exe a -tzip -p$pwd $zipfile $filearch");
?>


Bookmark and Share

Getting MAC Address using PHP


Getting MAC Address using PHP
In this article,I will explain how to get MAC address in PHP using Simple php script.
How can I get the MAC and the IP address using PHP.


Example:
<?php
ob_start(); 
system("ipconfig /all"); 
 $cominfo=ob_get_contents(); 
ob_clean(); 
$search = "Physical";
$primarymac = strpos($cominfo, $search); 
$mac=substr($cominfo,($primarymac+36),17);//MAC Address
echo $mac;
?>


Output:
10-AA-CC-55-3B-BB


Bookmark and Share

Difference between sort(), asort() and ksort in php

Difference between sort(), asort() and ksort in php

sort():
sorts an array by the values.

Syntax
sort(arr,type)

Example:
<?php
$arr = array("a" => "Blue", "b" => "White", "c" => "Orange");
sort($arr);
print_r($arr);
?>
Output:
Array
(
[0] => Blue
[1] => Orange
[2] => White
)


Bookmark and Share

php register_globals on/off in php.ini

PHP register_globals on/off
  • The register_globals setting controls how you access form,server, and environment variables. 
  • By default this variable is set to Off.
  • When on, register_globals will inject your scripts with all sorts of variables.
  • when register_globals is set to ON in php.ini.you don’t need to write $_POST['var'] to access the posted ‘var’ variable you can simply use ‘$var’ to access the $_POST['var'].

It's preferred to use $GLOBALS,$_SERVER,$_GET,$_POST,$_FILES,$_COOKIE,$_SESSION,
$_REQUEST,$_ENV, rather than relying upon register_globals being on.


please check below link to view complete details:
php register_globals FAQ


Bookmark and Share

Difference between accessing a class method via -> and via :: ?


What's the Difference between accessing a class method via -> and via ::?
The -> is used for accessing properties and methods of instantiated objects.
:: is used for accesing static methods or attributes and don't require to instantiate an object of the class.

Example:
<?php
class Person
{
  var $name = Raj; 


  public function getName()
  {
    return $this->name;
  }


  public static function getAge()
  {
    return "25";
  }
}
$person = new $person(); 
echo $person->getName();//Require to instantiate an object of the class.
echo person::getAge();//:: is used for accesing static methods(getAge), so don't require to instantiate an object of the  class
?>
Output:
Raj 25


Bookmark and Share

Select list add and remove in php using jquery

Select list add and remove in php using jquery:
In this article,I will show how to select list add and remove in PHP using Jquery with simple example.
Suppose I have 2 list box . The first box is populated with Characters. I have two buttons (add, remove). When the button is press it take the select element from list1 and put it in list2.


Example:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function() {
  $(".middle input[type='button']").click(
function(){
    var listArr = $(this).attr("name").split("_");
    var list1 = listArr[0];
    var list2 = listArr[1];
    $("#" + list1 + " option:selected").each(function(){
      $("#" + list2).append($(this).clone());
      $(this).remove();
    });
  });
})
</script>
<table width=50%>
<tr>
<td>
    <select name="items1" id="first" size="5" multiple="multiple">    
      <option value="1">A</option>
      <option value="2">B</option>
      <option value="3">C</option>
      <option value="4">D</option>
      <option value="5">E</option>
    </select>
</td>
<td>
  <div class="middle">
     <input name="first_second" value=">>" type="button">
    <input name="second_first" value="<<" type="button">
  </div>
</td>
<td>
  <select name="items" id="second" size="5" multiple="multiple">
    </select>
 </td>
</tr>
</table>
</body>
</html>



Bookmark and Share

Difference between __sleep and __wakeup in php

Difference between __sleep and __wakeup in php


__sleep returns the array of all the variables than need to be saved.
__wakeup retrieves them.
__sleep() and __wakeup() run prior to serialize() and unserialize() respectively.

Example:

<?php
class DBConn
{
    protected $conn;
    private $host, $username, $password, $db;
    
    public function __construct($host, $username, $password, $db)
    {
        $this->host = $host;
        $this->username = $username;
        $this->password = $password;
        $this->db = $db;
        $this->connect();
    }
    
    private function connect()
    {
        $this->conn = mysql_connect($this->host, $this->username, $this->password);
        mysql_select_db($this->db, $this->conn);
    }
    
    public function __sleep()
    {
        return array('host', 'username', 'password', 'db');
    }
    
    public function __wakeup()
    {
        $this->connect();
    }
   
    $c=new DBConn("localhost","root","","testdb");
    $c->__wakeup();


}
?>


Bookmark and Share

How can get current year in php

How can get current year in php.
In this article,I will show how to get Current Year in PHP.

The PHP Date() Function:
The PHP date() function formats a date and time.

Syntax
date(format,timestamp)

 d - Represents the day of the month (01 to 31)
 m - Represents a month (01 to 12)
 Y - Represents a year (e.g.2012)

Example:

<?php
echo $date=date('Y');//Get Current Year in PHP
?>

Output:
2012.


Bookmark and Share

Convert a three digit integer to an array in php

How do I convert a three digit integer to an array so that each digit is in its own element?


In this article, I will show how to convert a three digit integer to an array so that each digit is in its own element.
we are using php str_split() Function.

PHP str_split() function :
The str_split() function splits a string into an array.


Syntax
str_split(string,length) 


Example:
<?php

$string="123";
$arr=str_split($string);
print_r($arr);


?>
Output: Array ( [0] => 1 [1] => 2 [2] => 3 ) 


Bookmark and Share