NEWS & UPDATES >> BCA BCSP064 Synopsis & Project Work Started for DEC 2017, IGNOU MCA MCSP060 Synopsis Work Started for DEC 2017, CONTACT 4 IGNOU Mini Project
Showing posts with label PHP-MySQL. Show all posts
Showing posts with label PHP-MySQL. Show all posts

Arrays in PHP by NiPS Institute Best Coaching Institute in New Delhi

What are the Arrays in PHP

An array is a collection of values in a single variable name.The variables in an array is called the array elements.Array elements are accessed using a single name and an indexed number represending the postion of the elements with in the array.The lenght of an array will be less than the actual length.Since index is starts with zero.We can insert the values for each elemnets in an array by using a subscript as follows,
<?php
$a [0] = "apple";
$a [1] = "cherry";
$a [2] = "plum";
?>
We can also use array() function to declare an array of predifined values
<?php
$a = array("apple","cherry","plum");
?>
Values taken from the array is similar to assign values to the array.
<?php
$abc = $a[2];
?>
Now the value of the variable $abc will be "plum" , Loops are widely used to manipulate the arrays.The following code is used for assigning and printing the values in an array.
<?php
for($i=1;$i<=10;$i++) { $arr [$i] = $i*$i; echo $arr [$i]; }
?>
There are three types of arrays in php:-
  1. Numeric(Indexed) array - An array with a numeric index
  2. Associative array - An array where each ID key is associated with a value
  3. Multidimensional array - An array containing one or more arrays

Numeric Array

Numeric or Indexed array has numeric keys that start with zero.Any kind of values can be assigned in the elements of the array.The following code shows how to assigning values to an indexed array. 
<?php
$a = array("apple","cherry","plum"); 
?>
Or 
<?php
$a [0] = "apple";
$a [1] = "cherry";
$a [2] = "plum"; 
?>

Associative Array

In associative array we can use user defined keys (named keys) for assigning values to the array.The usage of associative array is given below. 
<?php
$a["apple"]="Rs.72";
$a["grape"]="Rs.152";
$a["cherry"]="Rs.350"; 
?>

Multidimensional Array

A multidimensional array is an array that contains at least one other array as the value of one of the indexes.
<?php
$MDA= array(
"A" => array(0 => "red", 2 => "blue", 3 => "green"),
"B" => array(1 => "orange", 2 => "black"),
"C" => array(0 => "white", 4 => "purple", 8 => "grey")
);

echo $MDA["A"][3]; // green
echo "<br>";
echo $MDA["C"][8]; // grey
?>

Arrays in PHP by NiPS Institute Best Coaching Institute in New Delhi

Function in PHP by NiPS Institute Best Coaching Institute in New Delhi

  1. Write Down Function in PHP

  2. Besides control and variables are PHP scripts through function calls. If the same code is executing this program code is often outsourced to a function. So instead of having the same code every time you call in the appropriate places on only the function, which then performs the actual work.
    The behavior of a function is affected by their parameters. A function can have any number of parameters, including parameters not exactly as an infinite number of parameters. Further, a function return value. This is also the standard use of a function, it will pass parameters and the function returns a value based on this back. For example, the sin function returns the sine of the given radian value.
    <?php
    sin(3.1415);
    ?>
  3. Define your own functions
    Sooner or later we want not only the functionality provided by using special PHP define your own functions. A function definition starts with the keyword function in PHP.
    <? Php
    function
    ?>
    This is followed by the actual name of the function. The name itself is subject to common rules such as not begin with numbers. Furthermore, the functions have two underscores (__) begin special functionality. You should use this function only when they want exactly the functionality that is described in the manual.
    <? Php
    function myFunction
    ?>
    Like a function call now follows an open parenthesis (. According to the clamp can now variables for the parameters are given. With the number of variables (comma separated) so you need to decide the number of parameters. However if you are planning a function with any to define many parameters you are at this point no parameters at all and use the functions in the function body func_get_args, func_get_arg and func_num_args. The parameter list is then finished with the closing parenthesis).
    <? Php
    function myFunction ($ param1, $ param2)
    ?>
    The contents of the function starts with an opening curly brace {. Now you can write any PHP code. At the end of the function body ends with a closing curly chamber }.
    <? Php
    function myFunction ($ param1, $ param2) {
       / / Here now follows
       / / Normal php code
    }
    ?>
    For typical programming style to indent the code within the function by 4 spaces. Thus it can be seen where the function starts (the function keyword) and where it ends (at the closing brace}).
    Within the function, the parameter variables can be used. In addition to the superglobal variables no further variables are otherwise available. This is called also variable scope. The variable parameters are then filled in accordance with the values ​​of the function call. If the parameters for the function are variables whose values ​​are passed, but not the variable itself in first place, it is therefore not possible to change variables that are used outside the function.
    <? Php
    function myFunction () {
       echo $ var / / help, where is defined $ var?
    }
    $ Var = 'HTML';
    myFunction () / / will not work because the only function parameters and variables
                    / / Super globals are available
    ?>
    3 Optional parameters
    In PHP, it is allowed to define which one is not used later in a function call parameters. Thus it is e.g. possible to call the function although theoretically supports 3 parameters a function with only one parameter. So as to define a function assigns default values ​​to the parameters in the parameter list. It is done by specifying an assignment for the parameter. When the function is called with a parameter value that is used for the variable parameters. When the function is called without the parameter as the parameter variable contains the specified default value.
    <? Php
    function myFunction ($ x, $ test = 'foobar') {
       echo 'x has the value: "' $ x.. '" test and has the value: "' $ test.. '"';
    }
    myFunction (4, 'word') / / outputs 4 and word of
    myFunction (5) / / outputs 5 and foobar
    myFunction () / / not possible since at least one parameter is required
    myFunction (1, 2, 3) / / possible, but the third parameter is lost
    ?>
    4 Return value of functions
    Although you use any functions in PHP code, as well as echo, it is customary return a calculated value for a function. This is implemented in PHP with the language construct return. It got to a value or a variable that you want to return.
    <? Php
    function myFunction () {
       do_that () / / is still running
       return 300;
       mach_das () / / is not running, as was leaving the function / closed
    }
    echo myFunction () / / outputs 300 from
    ?>
    With the return function is terminated at the same time. This can be done at any point, if it makes sense. In calculating the sine of the value 0 for example be expected not great but there is a case distinction quite early to the value 0 is returned.
    It is also possible to exit a function and return with it to indicate no return value. This makes only sense if not expected is that a function has a return value.
    <? Php
    function myFunction () {
       / / Code anderere
       return;
    }
    myFunction () / / works without problems
    My $ var = function () / / works, $ var got the value NULL (a special data type)
    ?>
    5 Documentation of own functions
    Functions that are provided by PHP described in detail on the official website. Accordance with specially created features missing such a documentation. You may guess the functionality of the function name. For complex functions are hoping for a good documentation. For this purpose they PHPDocs. Before the actual function to add a PHPDoc comment which describes the function.
    <? Php
    / **
    * Returns a square number.
    *
    * This function is passed a parameter and returns
    * Square of this function back.
    *
    * @ Param x The value of the you want to have a perfect square
    * @ Return The number of square
    * /
    function square ($ x) {
       return $ x * $ x;
    }
    ?>  Function in PHP by NiPS Institute Best Coaching Institute in New Delhi

Loops in PHP By NiPS Ignou BCA MCA Coaching Institute in Delhi

Loops in PHP By NiPS Ignou BCA MCA Coaching Institute in Delhi

What are various Loops in PHP

Sometimes we need execute some code repetitively based on a condition. In this situation we can use loops to perform that task.
In PHP, we have the following looping statements:
  • while - loops through a block of code until specified condition is true
  • do...while - loops through a block of code once, and then repeats the loop until the specified condition is true
  • for - loops through a block of code a specified number of times
  • foreach - loops through a block of code for each element in an array

while loop

The while loop is used to execute a block of statements for a definite number of times, depending on a condition. The while loop statement always checks the condition before executing the statement with in the loop.The loop will continues its the execution until the condition evaluates to false.
Example
<?php
$a=1;
while($a<=10)
 {
 echo "The number is:     $a<br>";
 $a++;
 }
?>

do ... while Loop

This loop is a same as the while loop, The do  block will executes at least once in the begining of the loop.
do
 {
 code to be executed;
 }
while (condition is true);

For loop

The for loop is used to execute the code for a specific number of times.The same procedure as for loop.
for (init counter; test counter; increment counter)
 {
 code to be executed;
 }
The initialization expression initialize the expression for the for loop statement.It executes once at the begining of the loop. The termination expression determines when to terminate the while loop. At the beginning of the loop, this expression evaluated for each iteration. if the expression evaluates to false, the loop terminates. Then, the decrement/increment expression gets invoked after each iteration.

foreach Loop

The foreach loop only used to loop through array, It iterate for each key/value pair in an array.
foreach ($array as $value)
 {
 code to be executed;
 }

PHP Q/A by NiPS Ignou best Coaching Institute in Delhi

What are the Assignment operators & Other Operators in PHP

These operators are used to perform arithmetic operations to assign a value to an operand. Left operand gets set to the value of the expression on the right.
Example
Usage
Description
=
$a = 10;
Stores the value 10 in the variable $a

+=
$a += $b;
Same as
$a = $a +$b;
-=
$a -= $b;
Same as
$a = $a - $b;
*=
$a *= $b;
Same as
$a = $a * $b;
/=
$a /= $b;
Same as
$a = $a / $b;
%=
$a %= $b;
Same as
$a = $a % $b;

Unary operators

These operators are used to increment or decrement the value of an operand by1. The following table explain the usage of the increment and decrement operators.
operator
Description
Example
++
Used to increment the value of an operand by 1
$a = $b++;

--
Used to decrement the value of an operand by 1
$a = $b--;


Comparison operators

These operators are used to compare two values and execute a code block or an action on the basis of the result of that comparison. The result of the comparison operator will be ‘true’ or ‘false’
Operator
Usage
Description
Example
<
expression1 < expression2
It is used to check whether expression1 is less than expression2
$x < $y
 
True if $x is less than $y
>
expression1 > expression2
It is used to check whether expression1 is greater expression2
$x > $y
 
True if $x is greater than $y
<=
expression1 <= expression2
It is used to check whether expression1 is less than or equal to expression2
$x <= $y
 
True if $x is less than or equal to $y
>=
expression1 >= expression2
It is used to check whether expression1 is greater than or equal to expression2
$x >= $y
 
True if $x is greater than or equal to $y
==
expression1 == expression2
It is used to check whether expression1 is equal to expression2
$x == $y
 
True if $x is equal to $y
!=
expression1 != expression2
It is used to check whether expression1 is not equal to expression2
$x != $y
 
True if $x is not equal to $y
===
expression1 === expression2
It is used to check whether expression1 is identical to expression2
$x === $y
True if $x is equal to $y, and they are of the same type

Logical operators

These operators are used to evaluate expressions and return a boolean value.
Operator
Usage
Description
Example
&&
expression1 && expression2
It returns true, if both expression1 andexpression2 are true.
$x && $y
 
True if both $x and $y are true
!
! expression
It returns true, if expression is false.
!$x
 
True if $x is not true
||
expression1 || expression2
It returns true, if either expression1 orexpression2 or both of them are true.
$x || $y
 
True if either $x or $y is true

IGNOU Best coaching institute for MCA Provides PHP Q/A

NiPS Institute is IGNOU Best coaching institute for BCA MCA Program  Provides PHP Q/A for IGNOU Students

What are the Operators in php 

Php applications use operators to process the data that entered by a user or fetch from the database. Operators like + and – are used to process variables and return a value. It is used for computations or comparisons and it may contain one or more characters. Operators can transform one or more data values called operands, into a new data value.
Consider the following example:
$a+$b
The preceding example uses two operands and an operator to add the values stored in the variables.
Following operators used in php
1.      Arithmetic operators
2.      Assignment operators
3.      Unary operators
4.      Comparison operators
5.      Logical operators
6.      Array operators

Arithmetic operators

These operators are the symbols that are used to perform arithmetic operations on the php variables. The following table describes the commonly used arithmetic operators.
Operators
Description
Example
+
Used to add to numbers
$a = $b+$c;
If  $b is equal to 10 and $c is equal to 5,Then $a will be 15
-
Used to subtract two numbers
$a = $b-$c;
If  $b is equal to 10 and $c is equal to 3,Then $a will be 12
*
Used to multiple two numbers
$a = $b*$c;
If  $b is equal to 8 and $c is equal to 5,Then $a will be 40
/
Used to divide one number by another
$a = $b/$c;
If  $b is equal to 8 and $c is equal to 2,Then $a will be 4
%
Used to divide two numbers and return the reminder
$a = $b%$c;
If  $b is equal to 21 and $c is equal to 2,Then $a will be 1

IGNOU BCA Best Coaching Institute NiPS Provide PHP Q/A



What are the Conditional Statements in PHP

If else statement

The if .. else construct is used to take decision based on the Boolean result that return by a logical expression.

We can use the if ...else block as following examples.

Example 1
if ($val==1)
 {
        echo “The result is 1”;
 }
Example 2
if ($val==’Ram’)
 {
        echo “Your name is Ram”;
 }
else
{
    echo “Your are not Ram”;
}
Example 3
if ($val==’Ram’)
 {
        echo “Your name is Ram”;
 }
else if ($val==’Jo’)
{
    echo “Your name is jo”;
}
else
{
    echo “Name not found”;
}

switch case statement

switch case is the another conditional statement in php.It is used when we need to compare multiple values of a variable. You can use the switch case statement as following.
<?php
    $name="Sijo";
    switch ($name)
    {
    case "Sijo":
      echo "Your name is Sijo";
      break;
    case "Dinson":
      echo "Your name is Dinson";

      break;
    case "Manu":
      echo "Your name is Manu";
      break;
    default:
      echo "Name not faound";
    }
    ?>
Whenever the switch statement is executed,the variable given in the switch statement is evaluated and compared with each case constant. If one of the case constant is equal to the value of the variable given in the switch statement, control is passed to the statement following the matched case label. A break  statement is used to exit the switch statement.If none of the cases match,the default case is invoked.

IGNOU BEST COACHING INSTITUTE IN DELHI NIPS INSTITUTE COLLABORATED WITH IGNOUFRIEND TO PROVIDE FREE SUPPORT AND SOLUTION TO IGNOU BCA MCA STUDENTS

Thanks NiPS Institute for IGNOU BCA MCA Students

PHP interview questions and answers for freshers

IGNOU Best Coaching Institute in Delhi NiPS Institute collaborated with IGNOUFriend to Provide free support and solution to IGNOU BCA MCA Students

Thanks NiPS Institute for IGNOU BCA MCA Students

Question : What is PHP and Its variable

PHP is a programming language,It is used for making dynamic and interactive Web pages. PHP is a widely-used, free ans easy to learn.Before you continue you should have a basic knowledge in HTML and javascript.whenever we need to create a dynamic html file, we need to create a file contain our program logic as a php script with .php as the extension, we can add html tags and javascript etc in the same file.PHP file can open,read or close file in server and establish a database connection and query something from the database, anything can do like other scripting languages such as ASP,JSP etc
The php script executed on the web server such as apache server and return html to the browser

example: <?php echo "Hello world"; ?>
This script print "Hello world" in your browser as output. The echo is a function used to print a value in the out put html
Every code line in PHP must end with a semicolon. The semicolon is a separator between the instructions from another.If you forgot to put a semicolon,php compiler will return an error 


Question : What are the PHP Variables

A variable is a memory location to store a value.In PHP the value may be a string,number,flot,array even an object of a class etc. A variable begins with the $ sign
Rules for declare PHP variables:
  • A variable begins with the $ sign,followed by its name
  • A variable name must start with a letter or _ charactor
  • A variable name can only contain letters , number and _ charactor (A-z,0-9, and _)
  • Variable names are case sensitive $y not equal $Y
System allocated a space for a variable only when you assign a value for it
<?$txt="Hello world!";
$x=5;?> .


Question : How to write Comments in PHP

We can write comments in php script like the following
<?php
// This type comment is used to write a single line comment
echo “Hello php”;
/*
This is
a PHP comment
block
*/
?>

IGNOU Best Coaching Institute NiPS Provides PHP Q/A

PHP QUESTION ANSWER BY IGNOU BEST COACHING INSTITUTE IN DELHI NIPS INSTITUTE 


For IGNOUFriend & IGNOU BCA MCA Students


How to create a text file in php?
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" ); exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );

How to strip whitespace (or other characters) from the beginning and end of a string ?
The trim() function removes whitespaces or other predefined characters from both sides of a string.

 What is the use of header() function in php ?
The header() function sends a raw HTTP header to a client browser.Remember that this function must be called before sending the actual out put.For example, You do not print any HTML element before using this function.

How to redirect a page in php?
The following code can be used for it, header("Location:index.php");

How stop the execution of a php scrip ?
exit() function is used to stop the execution of a page

   How to set a page as a home page in a php based site ?
index.php is the default name of the home page in php based sites

How to find the length of a string?
strlen() function used to find the length of a string

what is the use of rand() in php?
It is used to generate random numbers.If called without the arguments it returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 6 and 12 (inclusive), for example, use rand(6, 12).This function does not generate cryptographically safe values, and should not be used for cryptographic uses. If you want a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.

what is the use of isset() in php?
This function is used to determine if a variable is set and is not NULL

What is the difference between mysql_fetch_array() and mysql_fetch_assoc() ?
mysql_fetch_assoc function Fetch a result row as an associative array, Whilemysql_fetch_array() fetches an associative array, a numeric array, or both

What is mean by an associative array?
Associative arrays are arrays that use string keys is called associative arrays.

What is the importance of "method" attribute in a html form?
"method" attribute determines how to send the form-data into the server.There are two methods, get and post. The default method is get.This sends the form information by appending it on the URL.Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

What is the importance of "action" attribute in a html form?
The action attribute determines where to send the form-data in the form submission.

What is the use of "enctype" attribute in a html form?
The enctype attribute determines how the form-data should be encoded when submitting it to the server. We need to set enctype as "multipart/form-data"when we are using a form for uploading files

How to create an array of a group of items inside an HTML form ?
We can create input fields with same name for "name" attribute with squire bracket at the end of the name of the name attribute, It passes data as an array to PHP.
For instance :
<input name="MyArray[]" />  <input name="MyArray[]" />  <input name="MyArray[]" />  <input name="MyArray[]" />

Define Object-Oriented Methodology
Object orientation is a software/Web development methodology that is based on the modeling a real world system.An object is the core concept involved in the object orientation. An object is the copy of the real world enity.An object oriented model is a collection of objects and its inter-relationships

How do you define a constant?
Using define() directive, like define ("MYCONSTANT",150)

How send email using php?
To send email using PHP, you use the mail() function.This mail() function accepts 5 parameters as follows (the last 2 are optional). You need webserver, you can't send email from localhost. eg : mail($to,$subject,$message,$headers);

 How to find current date and time?
The date() function provides you with a means of retrieving the current date and time, applying the format integer parameters indicated in your script to the timestamp provided or the current local time if no timestamp is given. In simplified terms, passing a time parameter is optional - if you don't, the current timestamp will be used.

Difference between mysql_connect and mysql_pconnect?
There is a good page in the php manual on the subject, in short mysql_pconnect() makes a persistent connection to the database which means a SQL link that do not close when the execution of your script ends. mysql_connect()provides only for the databasenewconnection while using mysql_pconnect , the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection... the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use.

What is the use of "ksort" in php?
It is used for sort an array by key order.

What is the difference between $var and $$var?
They are both variables. But $var is a variable with a fixed name. $$var is a variable who's name is stored in $var. For example, if $var contains "message", $$var is the same as $message.

What are the encryption techniques in PHP
MD5 PHP implements the MD5 hash algorithm using the md5 function,
eg : $encrypted_text = md5 ($msg);
mcrypt_encrypt :- string mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] );
Encrypts plaintext with given parameters

What is the use of the function htmlentities?
htmlentities Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

 How to delete a file from the system
Unlink() deletes the given file from the file system.

How to get the value of current session id?

session_id() function returns the session id for the current session.

IGNOU Best Coaching Institute in delhi NiPS Provide PHP Q/A

PHP QUESTION ANSWER BY IGNOU BEST COACHING INSTITUTE IN DELHI NIPS INSTITUTE 


For IGNOUFriend & IGNOU BCA MCA Students

What’s the difference between include and require?
It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

 What is the difference between Session and Cookie?
The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user’s computers in the text file format. Cookies can not hold multiple variables,But Session can hold multiple variables.We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking

How to set cookies in PHP?
Setcookie("sample", "ram", time()+3600);

How to Retrieve a Cookie Value?
eg : echo $_COOKIE["user"];

How to create a session? How to set a value in session ? How to Remove data from a session?
Create session : session_start();
Set value into session : $_SESSION['USER_ID']=1;
Remove data from a session : unset($_SESSION['USER_ID'];

what types of loops exist in php?
for,while,do while and foreach (NB: You should learn its usage)

How to create a mysql connection?
mysql_connect(servername,username,password);

How to select a database?
mysql_select_db($db_name);

How to execute an sql query? How to fetch its result ?
$my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; ");
$result = mysql_fetch_array($my_qry);
echo $result['First_name'];

Write a program using while loop
$my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; ");
while($result = mysql_fetch_array($my_qry))
{
echo $result['First_name'.]."<br/>";
}

How we can retrieve the data in the result set of MySQL using PHP?
o    1. mysql_fetch_row
o    2. mysql_fetch_array
o    3. mysql_fetch_object
·         4. mysql_fetch_assoc

  What is the use of explode() function ?
Syntax : array explode ( string $delimiter , string $string [, int $limit ] );
This function breaks a string into an array. Each of the array elements is a substring of string formed by splitting it on boundaries formed by the string delimiter.

What is the difference between explode() and split() functions?
Split function splits string into array by regular expression. Explode splits a string into array by string.

  What is the use of mysql_real_escape_string() function?
It is used to escapes special characters in a string for use in an SQL statement

Write down the code for save an uploaded file in php.
if ($_FILES["file"]["error"] == 0)
{
move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}