Showing posts with label PHP interview questions and answers. Show all posts
Showing posts with label PHP interview questions and answers. Show all posts

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

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

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

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

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

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

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

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