Saturday, 30 November 2013

Login Code in PHP

In this tutorial, we create 3 php files for testing our code.

1. index.php
2. logincheck.php
3. success.php

4 Steps to create login page

1. Create table "userlist" in database "demo".
2. Create file index.php.
3. Create file logincheck.php.
4. Create file success.php.

Create file index.php.


<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form" method="post" action="logincheck.php">
<td>
<table width="100%" border="0" cellpadding="2" cellspacing="2" bgcolor="#000">
<tr>
<td colspan="3"><strong>Login Page</strong></td>
</tr>
<tr>
<td width="78">Userid / Email id</td>
<td width="6">:</td>
<td width="294"><input name="txtusername" type="text" id="txtusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="txtpassword" type="text" id="txtpassword"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

Creating database with table and data


CREATE TABLE `userlist` (
`id` int(4) NOT NULL auto_increment,
`username` varchar(65) NOT NULL default '',
`password` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;

INSERT INTO `userlist` VALUES (1, 'admin', 'admin123');


Create logincheck.php page

<?php

$host="localhost"; // Host name
$username=""; // username
$password=""; // password
$dbname="demo"; // Database name
$tblname="userlist"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");

// username and password sent from form
$txtusername=$_POST['txtusername'];
$txtusername=$_POST['txtpassword'];

// To protect MySQL injection (more detail about MySQL injection)
$txtusername= stripslashes($txtusername);
$txtusername= stripslashes($txtusername);
$txtusername= mysql_real_escape_string($txtusername);
$txtusername= mysql_real_escape_string($txtusername);
$sql="SELECT * FROM $tblname WHERE username='$txtusername' and password='$txtusername'";
$result=mysql_query($sql);

// Counting table row
$row=mysql_num_rows($result);

// If  matched $txtusernameand $txtusername, table row must be 1 row
if($row==1){

// Register redirect to file "success.php"
session("txtusername");
session("txtusername");
header("location:success.php");
}
else {
echo "Invalid Username or Password";
}
?>

Create Success Page


<?php
session_start();
if(!session_is_registered(txtusername)){
header("location:index.php");
}
?>

<html>
<body>
Login Successful
</body>
</html>

PHP database Connection


<?php
$dbhost = 'localhost:1080';
$dbuser = 'username'; // in local root is default username
$dbpass = 'password';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $con )
{
  die('connection error : ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'CREATE Database test_database';
$query= mysql_query( $sql, $conn );
if(! $query )
{
  die('Not create database: ' . mysql_error());
}
echo "Database created successfully\n";
mysql_close($conn);
?>

Mail Function in PHP

How to send mail in php

Mail Function in PHP


<html>

<body>

<?php

if (isset($_REQUEST['email']))

//if "email" is filled out, send email

  {

  //send email

  $email = $_REQUEST['email'] ;

  $subject = $_REQUEST['subject'] ;

  $message = $_REQUEST['message'] ;

  mail("someone@example.com", "Subject: $subject",

  $message, "From: $email" );

  echo "Thank you for using our mail form";

  }

else

//if "email" is not filled out, display the form

  {

  echo "<form method='post' action='mailform.php'>

  Email: <input name='email' type='text'><br>

  Subject: <input name='subject' type='text'><br>

  Message:<br>

  <textarea name='message' rows='15' cols='40'>

  </textarea><br>

  <input type='submit'>

  </form>";

  }

?>

</body>

</html>


Mail Function in PHP

Image Uploading in PHP

how to upload Image in PHP

File Name save as form.php

<html>
<head>
<script type="text/javascript">
function validate(){
var filevalue=document.getElementById("file").value;
var description=document.getElementById("description").value;
if(filevalue=="" || filevalue.length<1){
alert("Select File.");
document.getElementById("file").focus();
return false;
}
if(description=="" || description.length<1){
alert("File Description must not be blank.");
document.getElementById("description").focus();
return false;
}

return true;
}
</script>
</head>
<body >
<h2 align="center" >File Upload</h2>
<form action="file_upload.php" method="post" enctype="multipart/form-data" onSubmit="return validate()" >
<table align="center" >
<tr>
<td><label for="file">File:</label></td>
<td><input type="file" name="file" id="file" /></td>
</tr>
<tr>
<td><label >File Description:</label></td>
<td><input type="text" name="description" id="description" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit" /></td>
</tr>
<table>
</form>
</body>
</html>

Second File Name save as file_upload.php

?php
include("connect.php"); //database connection
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 1000000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "File Error : " . $_FILES["file"]["error"] . "<br />";
}
else {

echo "Upload File Name: " . $_FILES["file"]["name"] . "<br />";
echo "File Type: " . $_FILES["file"]["type"] . "<br />";
echo "File Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "File Description:: ".$_POST['description']."<br />";

if (file_exists("images/".$_FILES["file"]["name"]))
{
echo "<b>".$_FILES["file"]["name"] . " already exists. </b>";
}else
{
move_uploaded_file($_FILES["file"]["tmp_name"],"images/". $_FILES["file"]["name"]);

$loc="images/".$_FILES["file"]["name"];
$qu="insert into images.img(loc) values('$loc')";
mysql_query($qu,$con);
?>
Uploaded File:<br>
<img src="images/<?php echo $_FILES["file"]["name"]; ?>" alt="Image path Invalid" >
<?php
}
}
}else
{
echo "Invalid file detail ::<br> file type ::".$_FILES["file"]["type"]." , file size::: ".$_FILES["file"]["size"];
}
?>

Database


Database name: image
Table name : img
Table fields : imgid(int primary key, auto incr) , loc(varchar)

Wednesday, 26 June 2013

Disable Right Click, Ctrl+c and Ctrl+u



<script type="text/javascript">
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
var isCtrl = false;
    document.onkeyup=function(e)
    {
    if(e.which == 17)
    isCtrl=false;
    }
    document.onkeydown=function(e)
    {
    if(e.which == 17)
    isCtrl=true;
    if((e.which == 85) || (e.which == 67) && isCtrl == true)
    {
    // alert(‘Keyboard shortcuts are cool!’);
    return false;
    }
    }
</script>


this above code copy and paste in your head its Disabled Right click, Ctl+C and Ctl+U 


Differences Between Two Dates or Timestamps in PHP


<?php
/*for finding date different begins here*/
  // Set timezone
  date_default_timezone_set("UTC");

  // PHP strtotime compatible strings
  function dateDiff($time1, $time2, $precision = 6) {
    // If not numeric then convert texts to unix timestamps
    if (!is_int($time1)) {
      $time1 = strtotime($time1);
    }
    if (!is_int($time2)) {
      $time2 = strtotime($time2);
    }

    // If time1 is bigger than time2
    // Then swap time1 and time2
    if ($time1 > $time2) {
      $ttime = $time1;
      $time1 = $time2;
      $time2 = $ttime;
    }

    // Set up intervals and diffs arrays
    $intervals = array('minute');
    $diffs = array();

    // Loop thru all intervals
    foreach ($intervals as $interval) {
      // Create temp time from time1 and interval
      $ttime = strtotime('+1 ' . $interval, $time1);
      // Set initial values
      $add = 1;
      $looped = 0;
      // Loop until temp time is smaller than time2
      while ($time2 >= $ttime) {
        // Create new temp time from time1 and interval
        $add++;
        $ttime = strtotime("+" . $add . " " . $interval, $time1);
        $looped++;
      }

      $time1 = strtotime("+" . $looped . " " . $interval, $time1);
      $diffs[$interval] = $looped;
    }

    $count = 0;
    $times = array();
    // Loop thru all diffs
    foreach ($diffs as $interval => $value) {
      // Break if we have needed precission
      if ($count >= $precision) {
break;
      }
      // Add value and interval 
      // if value is bigger than 0
      if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
 $interval .= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
      }
    }

    // Return string with times
    return implode(", ", $times);
  }
 /*for finding date different end here*/
?>
/*for echo in php*/

<?php 
echo dateDiff("2010-01-26", "2004-01-26") . "\n";
echo dateDiff("2006-04-12 12:30:00", "1987-04-12 12:30:01") . "\n";
echo dateDiff("now", "now +2 months") . "\n";
echo dateDiff("now", "now -6 year -2 months -10 days") . "\n";
echo dateDiff("2009-01-26", "2004-01-26 15:38:11") . "\n";
?>

Monday, 17 June 2013

PHP Top Interview Questions and Answers

PHP Interview Questions and Answers 



Questions 1 :  Who is the father of PHP ?

Answers : Rasmus Lerdorf is known as the father of PHP.

Questions 2 : What is the difference between $name and $$name?

Answers :  $name is variable where as $$name is reference variable like $name=sonia and $$name=singh so $sonia value is singh.

Questions 3 :  How can we submit a form without a submit button?

Answer  :  Java script submit() function is used for submit form without submit button on click call document.formname.submit()

Questions 4 :  In how many ways we can retrieve the data in the result set of MySQL using PHP?
Answer :  We can do it by 4 Ways
 1. mysql_fetch_row. ,
 2. mysql_fetch_array ,
 3. mysql_fetch_object
 4. mysql_fetch_assoc

Questions 5 :  What is the difference between mysql_fetch_object and mysql_fetch_array?

Answers :  mysql_fetch_object() is similar tomysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Questions 6:  How can we extract string "pcds.co.in " from a string "http://info@pcds.co.in using regular expression of PHP?

Answers :  preg_match("/^http:\/\/.+@(.+)$/","http://info@pcds.co.in",$matches); echo $matches[1];

Questions 7 :  What are the differences between Get and post methods.

Answers :
  There are some defference between GET and POST method 1. GET Method have some limit like only 2Kb data able to send for request But in POST method unlimited data can we send 2. when we use GET method requested data show in url but Not in POST method so POST method is good for send sensetive request

Questions 8 :  How can we create a database using PHP and MySQL?

Answers : We can create MySQL database with the use of mysql_create_db("Database Name")

Questions 9 : What are the differences between require and include?

Answers :  Both include and require used to include a file but when included file not found Include send Warning where as Require send Fatal Error .

Questions 10 :  Can we use include ("xyz.PHP") two times in a PHP page "index.PHP"?

Answers :  Yes we can use include("xyz.php") more than one time in any page. but it create a prob when xyz.php file contain some funtions declaration then error will come for already declared function in this file else not a prob like if you want to show same content two time in page then must incude it two time not a prob

Questions 11: What are the different tables(Engine) present in MySQL, which one is default

Answers :  Following tables (Storage Engine) we can create

1. MyISAM(The default storage engine IN MYSQL Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type. An .frm file stores the table format. The data file has an .MYD (MYData) extension. The index file has an .MYI (MYIndex) extension. )
2. InnoDB(InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data.)
3. Merge
4. Heap (MEMORY)(The MEMORY storage engine creates tables with contents that are stored in memory. Formerly, these were known as HEAP tables. MEMORY is the preferred term, although HEAP remains supported for backward compatibility. )
5. BDB (BerkeleyDB)(Sleepycat Software has provided MySQL with the Berkeley DB transactional storage engine. This storage engine typically is called BDB for short. BDB tables may have a greater chance of surviving crashes and are also capable of COMMIT and ROLLBACK operations on transactions)
6. EXAMPLE 
7. FEDERATED (It is a storage engine that accesses data in tables of remote databases rather than in local tables. )
8. ARCHIVE (The ARCHIVE storage engine is used for storing large amounts of data without indexes in a very small footprint. )
9. CSV (The CSV storage engine stores data in text files using comma-separated values format.)
10. BLACKHOLE (The BLACKHOLE storage engine acts as a "black hole" that accepts data but throws it away and does not store it. Retrievals always return an empty result)

Questions 12:  What is use of header() function in php ?

Answers : The header() function sends a raw HTTP header to a client.We can use herder() function for redirection of pages. It is important to notice that header() must be called before any actual output is seen..

Questions 13: How can I execute a PHP script using command line?

Answers : Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument.

Questions 14:  Suppose your Zend engine supports the mode Then how can u configure your PHP Zend engine to support mode ?

Answers :  In php.ini file: set short_open_tag=on to make PHP support

Questions : 15 What is meant by nl2br()?

Answers :  Inserts HTML line breaks (<BR/>) before all newlines in a string

Questions 16 : What is htaccess? Why do we use this and Where?

Answers :  .htaccess files are configuration files of Apache Server which provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

Questions 17: How we get IP address of client, previous reference page etc ?Questions : 18 How we get IP address of client, previous reference page etc ?

Answers :  By using $_SERVER['REMOTE_ADDR'],$_SERVER['HTTP_REFERER'] etc.

Questions 18:  What are the reasons for selecting lamp (Linux, apache, MySQL, PHP) instead of combination of other software programs, servers and operating systems?

Answers :  All of those are open source resource. Security of Linux is very very more than windows. Apache is a better server that IIS both in functionality and security. MySQL is world most popular open source database. PHP is more faster that asp or any other scripting language.

Questions 19: How can we encrypt and decrypt a data present in a MySQL table using MySQL?

Answers  :  AES_ENCRYPT () and AES_DECRYPT ()

Questions 20 : What are the features and advantages of object-oriented programming?

Answers :  One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system

Questions 21:  What are the differences between procedure-oriented languages and object-oriented languages?

Answers :  There are lot of difference between procedure language and object oriented like below
  1. Procedure language easy for new developer but complex to understand whole software as compare to object oriented model 
  2. In Procedure language it is difficult to use design pattern mvc , Singleton pattern etc but in OOP you we able to develop design pattern 
  3. IN OOP language we able to ree use code like Inheritance ,polymorphism etc but this type of thing not available in procedure language on that our Fonda use COPY and PASTE
Questions 22:  What is the use of friend function?

Answers : Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class. A friend declaration is essentially a prototype for a member function, but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match.

Questions 23:  What is the functionality of the function strstr and stristr?

Answers :  strstr Returns part of string from the first occurrence of needle(sub string that we finding out ) to the end of string. $email= 'sonialouder@gmail.com'; $domain = strstr($email, '@'); echo $domain; // prints @gmail.com here @ is the needle stristr is case-insensitive means able not able to diffrenciate between a and A

Questions 24:  How can we convert the time zones using PHP?
Answer :  By using date_default_timezone_get and 
date_default_timezone_set function on PHP 5.1.0
<?php
// Discover what 8am in Tokyo relates to on the East Coast of the US    

// Set the default timezone to Tokyo time:
date_default_timezone_set('Asia/Tokyo');    

// Now generate the timestamp for that particular timezone, on Jan 1st, 2000
$stamp = mktime(8, 0, 0, 1, 1, 2000);    

// Now set the timezone back to US/Eastern
date_default_timezone_set('US/Eastern');    

// Output the date in a standard format (RFC1123), this will print:
// Fri, 31 Dec 1999 18:00:00 EST
echo '<p>', date(DATE_RFC1123, $stamp) ,'</p>';?>
';?>

Questions 25:  What is meant by urlencode and urldocode?

Answer : URLencode returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. urldecode decodes any %## encoding in the given string.

Questions 26: What is the difference between the functions unlink and unset?
Answer :  unlink() deletes the given file from the file system.
                 unset() makes a variable undefined.

Questions 27: What is the difference between ereg_replace() and eregi_replace()?

Answer :  eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.\

Questions 28:  How can I know that a variable is a number or not using a JavaScript?

Answer :  bool is_numeric ( mixed var) Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is not a number.

PHP Top Interview Questions and Answers 

Deference Between Page and Post in WordPress


Key Differences with Post and Page

The differences we list below definitely have exceptions. You can use plugins or code snippets to extend the functionality of both content types. Below is the list of key differences by default.

  1. Posts are timely vs. Pages are timeless. 
  2. Posts are social vs. Pages are NOT. 
  3. Posts can be categorized vs. Pages are hierarchical. 
  4. Posts are included in RSS feed vs. Pages are not. 
  5. Pages have custom template feature vs. Posts do not


Pages

Pages are meant to be static “one-off” type content such as your about page, privacy policy, legal disclaimers, etc. While the WordPress database stores the published date of the page, pages are timeless entities. For example, your about page is not suppose to expire. Sure you can go back and make updates to it, but chances are you will not have about page 2012, about page 2013 etc. Because there is no time and date tied to pages, they are not included in your RSS feeds by default. Pages are not meant to be social in most cases thus does not include social sharing buttons, or comments.

You don’t want users to comment on your contact page, or your legal disclaimers page. Just like you probably don’t want others to tweet your privacy policy page in most cases.

Unlike posts, pages are hierarchical by nature. For example, you can have a sub pages within a page. A key example of this in action would be our Blueprint page. This feature allows you to organize your pages together, and even assign a custom template to them.

WordPress by default comes with a feature that allows you create custom page templates using your theme. This allows developers to customize the look of each page when necessary. In most themes, post and pages look the same. But when you are using your page to create a landing page, or a gallery page, then this custom page templates feature comes in very handy.

Pages also have this archaic feature called Order which lets you customize the order of pages by assigning a number value to it. However this feature is extended by plugins like Simple Page Ordering that allows you to drag & drop the order of pages.

Post

If you are using WordPress as a blog, then you will end up using posts for majority of your site’s content. Posts are content entries listed in reverse chronological order on your blog’s home page. Due to their reverse chronological order, your posts are meant to be timely. Older posts are archived based on month and year. As the post gets older, the deeper the user has to dig to find it. You have the option to organize your posts based on categories and tags.

Because WordPress posts are published with time and date in mind, they are syndicated through the RSS feeds. This allows your readers to be notified of the most recent post update via RSS feeds. Bloggers can use the RSS feeds to deliver email broadcasts through services like Aweber or MailChimp. You can create a daily and weekly newsletter for your audience to subscribe to. The very timely nature of posts make it extremely social. You can use one of the many social sharing plugins to allow your users to share your posts in social media networks like Twitter, Facebook, Google+, LinkedIn etc.

Posts encourage conversation. They have a built-in commenting feature that allows users to comment on a particular topic. You can go to your Settings » Discussion to turn off comments on older posts if you like

Thursday, 13 June 2013

Difference Between HTML 4 and HTML 5


Today we take a few steps back and take a look at some of the differences between HTML 4 and HTML5. This is intended to be a useful overview, not an exhaustive reference, but remember that things are still and always changing. We can’t deny the fact that HTML4 is the most successful markup language in the history of Internet ever. HTML5 builds on that revolutionary success. To start coding with HTML5, you don’t need to change the way you used to code in HTML4. With HTML5 you have new semantic elements, direct support for audio, video and a cool new canvas feature.



1. HTML5 Is a Work in Progress

As cool as it is to see what HTML5 can do for you, it hasn’t been standardized like HTML4. You don’t have to worry about updating pages built using HTML4. It’s more than ten years old and it’s a set standard.

If you jump into HTML5 with both feet, you’re going to be making updates. Elements and attributes are added and modified several times a year. Of course, this is dependent how much you depend on rich elements, but it’s certainly a risk you must take into consideration when using a fluid language.

Build with HTML4, play with HTML5

2. Simplified Syntax

The simpler doctype declaration is just one of the many novelties in HTML5. Now you need to write only: and this is it. The syntax of HTML5 is compatible with HTML4 and XHTML1, but not with SGML.

4. The and Elements

For good or bad, HTML5 has acknowledged the new web anatomy. With HTML5, and are specifically marked for such. Because of this, it is unnecessary to identify these two elements with a tag.

5. New and Elements
Again, HTML5 has adopted the popular web standard. and allows you to mark specific areas of your layout as such, and should have a positive effect on on your SEO in the end.

6. New and Elements

can be used for your main menu, but it can also be used for toolbars and context menus. The element is another way to arrange text and images.

7.New Forms

The new and elements are looking good. If you do much with forms, you may want to take a look at what these have to offer. 

Some Other Features
  1. HTML4 was developed by World Wide Web consortium and WHATWG (web hypertext application technology working group) and HTML5 is being developed by web hypertext application technology working group (WHATWG) and W3C HTML WG. 
  2. HTML5 brings in new elements to structure the web pages as compared to HTML4 which uses common structures such as: – header, columns etc. These new elements are: header, nav, section, article, aside, and footer.
  3. Now, each of these elements serves a unique purpose:- 
  • Header denotes the inclusion of heading, sub headings etc. which is more specific. 
  • Nav signifies both the website navigation as well as the navigation of the table of contents. 
  • Section element corresponds to a broad category of a web page. 
  • Article element symbolizes a particular section of web page such as: blog, news, testimonials etc. 
  • Aside element is used to include the content that may relate to a specific section of a document or a web page. 
  • Footer element is used to indicate important information like copyright data, the author’s name, links to other pages etc.
  1. HTML5 brings a whole new dimension to web world. It can embed video on web-pages without using any special software like Flash. 
  2. Not only videos, HTML5 is said to be capable of playing video games on the browser itself. 
  3. HTML5 is considered to be flexible to handle inaccurate syntax. HTML5 specifies the rules related to the parsing and lexing as compared to HTML4. This means that even if there is an incorrect syntax, similar result is produced by various complaint browsers. 
  4. Furthermore, HTML5 denotes to scripting of API (application programming interfaces) including new APIs like:- 

  • Drag and drop
  • Database storage offline
  • Editing of the document
  • Canvas 2D APIs, etc.

Differences Between C And C++


C++, as the name suggests, is a superset of C. As a matter of fact, C++ can run most of C code while C cannot run C++ code. Here are the 10 major differences between C++ & C

1. C follows the procedural programming paradigm while C++ is a multi-paradigm language(procedural as well as object oriented)
  • In case of C, importance is given to the steps or procedure of the program while C++ focuses on the data rather than the process. Also, it is easier to implement/edit the code in case of C++ for the same reason.
2. In case of C, the data is not secured while the data is secured(hidden) in C++
  • This difference is due to specific OOP features like Data Hiding which are not present in C.
3. C is a low-level language while C++ is a middle-level language (Relatively, Please see the discussion at the end of the post)
  • C is regarded as a low-level language(difficult interpretation & less user friendly) while C++ has features of both low-level(concentration on whats going on in the machine hardware) & high-level languages(concentration on the program itself) & hence is regarded as a middle-level language.
4. C uses the top-down approach while C++ uses the bottom-up approach
  • In case of C, the program is formulated step by step, each step is processed into detail while in C++, the base elements are first formulated which then are linked together to give rise to larger systems.
5. C is function-driven while C++ is object-driven
  • Functions are the building blocks of a C program while objects are building blocks of a C++ program.
6. C++ supports function overloading while C does not
  • Overloading means two functions having the same name in the same program. This can be done only in C++ with the help of Polymorphism(an OOP feature)
7. We can use functions inside structures in C++ but not in C.
  • In case of C++, functions can be used inside a structure while structures cannot contain functions in C.
8. The NAMESPACE feature in C++ is absent in case of C
  • C++ uses NAMESPACE which avoid name collisions. For instance, two students enrolled in the same university cannot have the same roll number while two students in different universities might have the same roll number. The universities are two different namespace & hence contain the same roll number(identifier) but the same university(one namespace) cannot have two students with the same roll number(identifier)
9. The standard input & output functions differ in the two languages
  • C uses scanf & printf while C++ uses cin>> & cout<< as their respective input & output functions
10. C++ allows the use of reference variables while C does not

  • Reference variables allow two variable names to point to the same memory location. We cannot use these variables in C programming.

Difference between php4 and php5

PHP5 introduces many new features, I have mentioned some of them:

Unified Constructors and Destructors:
In PHP4, constructors had same name as the class name. In PHP5, you have to name your constructors as __construct() and destructors as __destruct().

Abstract:
In PHP5 you can declare a class as Abstract.

Startic Methods and properties:
Static methods and properties are also available. When you declare a class member as static, then you can access members using :: operator without creating an instance of class.

 _autoload()
PHP5 introduces a special function called __autoload()
Final:
PHP5 allows you to declare a class or method as Final

Magic Methods
PHP5 introduces a number of magic methods. __call, __get, __set and __toString

Visibility:
In PHP5, There are 3 levels of visibilities:
    Public: Methods are accessible to everyone including objects outside the classes.
    Private: only available to the class itself.
    Protected: accessible to the class itself and inherited class.

Exception:
PHP5 has introduced ‘exceptions’(exception errors)

Passed by reference
In PHP4, everything was passed by value, including objects. Whereas in PHP5, all objects are passed by reference.

Interfaces: 
PHP5 introduces interfaces . An interface defines the methods a class must implement. All the methods defined in an interface must be public.

E_STRICT Error Level
PHP5 introduces new error level defined as ‘E_STRICT’ E_STRICT will notify you when you use depreciated code.

PHP5 also introduces new default extensions.
SimpleXML: for easy processing of XML data
DOM and XSL 
PDO . 
Hash :gives you access to a ton of hash functions.

PHP Interview Questions with Answers for Freshers


Q1. What is PHP stands for? 

 Ans. Hyper text Pre Processor

 Q2. What is PHP? 

 Ans. The PHP is a Hypertext Pre-processor and is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.

 Q3. Who is the Father of PHP? 

 Ans. Rasmus Lerdorf

 Q4. Which programming language does PHP resemble to? 

 Ans. PHP resemble to pearl and C

 Q5. What the difference is between include and require?

 Ans. Require () and include () are the same with respect to handling failures. However, require () results in a fatal error and does not allow the processing of the page. i.e. include will allow the script to continue.

 Q6. What is the current version of PHP? 

 Ans. php 5.4

 Q7. How can we create a database using PHP and MySQL?

 Ans. We can create MySQL database with the use of mysql_create_db ("Database Name")

 Q8.What Is a Session? 

 Ans.It can be used to store information on the server for future use.

 Q9. Is variable name case sensitive? 

 Ans. Yes variable name case sensitive and we cannot start a variable with number like $6name as a valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

 Q10. How can we execute a php script using command line?

 Ans. Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, "php myScript.php", assuming "php" is the command to invoke the CLI program

Wednesday, 12 June 2013

What is PHP?

PHP Introduction

About Php

PHP allows you to preform numerous mathematical tasks. You can do anything from simple addition to complex geometry. You can also do things like round numbers, convert bases, or find the absolute value of numbers.

  1. PHP stands for PHP: Hypertext Preprocessor
  2. PHP is a widely-used, open source scripting language
  3. PHP scripts are executed on the server
  4. PHP is free to download and use

What is a PHP File?
  1. PHP files can contain text, HTML, JavaScript code, and PHP code
  2. PHP code are executed on the server, and the result is returned to the browser as plain HTML
  3. PHP files have a default file extension of ".php"

Use For PHP
  1. PHP can generate dynamic page content
  2. PHP can create, open, read, write, and close files on the server
  3. PHP can collect form data 
  4. PHP can send and receive cookies
  5. PHP can add, delete, modify data in your database
  6. PHP can restrict users to access some pages on your website
  7. PHP can encrypt data

Why PHP Use

PHP runs on different platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is free. Download it from the official
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP is easy to learn and runs efficiently on the server side
PHP has support for a wide range of databases
PHP resource: www.php.net


What are the differences between PHP 4 and PHP 5?

While PHP 5 was purposely designed to be as compatible as possible with previous versions, there are some significant changes. Some of these changes include:

  • A new OOP model based on the Zend Engine 2.0
  • A new extension for improved MySQL support
  • Built-in native support for SQLite 
  • A new error reporting constant, E_STRICT, for run-time code suggestions 
  • A host of new functions to simplify code authoring (and reduce the need to write your own functions for many common procedures)
php tutorial

What is MySQL?

About MySQL ....


MySQL is the world's most popular open source database software,

 MySQL is a key part of LAMP (Linux, Apache, MySQL, PHP / Perl / Python), the fast-growing open source enterprise software stack. More and more companies are using LAMP as an alternative to expensive proprietary software stacks because of its lower cost and freedom from platform lock-in.

Our Continued MySQL Values

We want the MySQL database to be: 

  •  The best and the most-used database in the world for online applications
  •  Available and affordable for all 
  •  Easy to use
  •  Continuously improved while remaining fast, secure and reliable
  •  Fun to use and improve
  •  Free from bugs

  1. MySQL is a database system used on the web
  2. MySQL is very fast, reliable, and easy to use
  3. MySQL is ideal for both small and large applications
  4. MySQL is a database system that runs on a server
  5. MySQL compiles on a number of platforms
  6. MySQL is free to download and use
  7. MySQL is developed, distributed, and supported by Oracle Corporation
  8. MySQL supports standard SQL
  9. MySQL is named after co-founder Monty Widenius's daughter: My

For Download MySQL Database



MySQL Related To PHP

PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)


Like Queries

Select Username, UserID from Employee

Select * From Employee