Secret mind

hi Friends, I am Aman gupta and a web developer. I learned many languages such as java, javaScript, python, clang, php, jquery, mysql database, Html and css and many more just to make a perfect and wonderfully website. Here i will upload related post of PHP, Secret of world, computer science, Feelings, GK, And Question paper.

Trending video

Responsive Ads Here
‏إظهار الرسائل ذات التسميات PHP. إظهار كافة الرسائل
‏إظهار الرسائل ذات التسميات PHP. إظهار كافة الرسائل

الثلاثاء، 7 يناير 2020

PHP ultra important questions || secret mind

PHP ultra important questions 


Aman gupta


Q1 write a program to create a table and insert multipul records in the table.

Ans:

Create table:  

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// sql to create table
$sql = "CREATE TABLE aman (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {
    echo "Table aman created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}
$conn->close();
?>

Insert multipul records in the table: 

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO aman (firstname, lastname, email)
VALUES ('varun', 'meena', 'varun@example.com');";
$sql .= "INSERT INTO aman (firstname, lastname, email)
VALUES ('vandita', 'rajput', 'vandita@example.com');";
$sql .= "INSERT INTO aman (firstname, lastname, email)
VALUES ('shubham', 'podder', 'shubham@example.com')";
if ($conn->multi_query($sql) === TRUE) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>


Q2. write a program to update a record in the table.

Ans:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE tablename SET lastname='Doe' WHERE id=2";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
?>


Q3. write a programe to delete a record in the table.
Ans:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// sql to delete a record
$sql = "DELETE FROM tablename WHERE id=3";

if ($conn->query($sql) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>

Q4. Write a program to create a database.
Ans:
<?php
$servername = "localhost";
$username = "root";
$password = "";


// Create connection
$conn = new mysqli($servername,$username,$password);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "Create DATABASE demo";

if ($conn->query($sql) === TRUE) {
    echo "database has been cerated";
} else {
  echo "database has been not craeted".$conn->connect_error;
}

$conn->close();

?>

Q5.what is cookie? write a program to create a cookie and delete a cookie?
Ans:
clike me and see 7 question

Q6.What is session? How you can create session variable and print the value of session variable also write a program to delete or destroy a session.
Ans:  When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.

Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.

So; Session variables hold information about one single user, and are available to all pages in one application.


Start a PHP Session:
A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and set some session variables:

Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

Destroy a PHP Session:
To remove all global session variables and destroy the session, use session_unset() and session_destroy():

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session
session_destroy();
?>

</body>
</html>


Q7. Write a program to create and read a file.

Ans: PHP Create File - fopen(): 

The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files.

If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).

The example below creates a new file called "testfile.txt". The file will be created in the same directory where the PHP code resides:

Example
$myfile = fopen("testfile.txt", "w")


PHP Write to File - fwrite():

The fwrite() function is used to write to a file.

The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.

The example below writes a couple of names into a new file called "newfile.txt":

Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the string $txt that first contained "John Doe" and second contained "Jane Doe". After we finished writing, we closed the file using the fclose() function.

Q8. Explain the difference between the following 
  1. GET and POST method
  2. print and echo
  3. include and require statement 
Ans: 
  1.  --> clike me and see question number 2 <--
  2. *Clicke me and see question number 1*
  3. *clicke me and see question number 11*
Q9. what is function? explain all the types of functtion with example.

Ans:PHP | Functions:

A function is a block of code written in a program to perform some specific task. We can relate functions in programs to employees in a office in real life for a better understanding of how functions work. Suppose the boss wants his employee to calculate the annual budget. So how will this process complete? The employee will take information about the statics from the boss, performs calculations and calculate the budget and shows the result to his boss. Functions works in a similar manner. They take informations as parameter, executes a block of statements or perform operations on this parameters and returns the result.
PHP provides us with two major types of functions:

  • Built-in functions : PHP provides us with huge collection of built-in library functions. These functions are already coded and stored in form of functions. To use those we just need to call them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so on.
  • User Defined Functions : Apart from the built-in functions, PHP allows us to create our own customised functions called the user-defined functions.Using this we can create our own packages of code and use it wherever necessary by simply calling it.
 read more

Q10. What is array? Explain all the types of array with example.

Ans: An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

There are three different kind of arrays and each array value is accessed using an ID c which is called array index.

  • Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
  • Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
  • Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices

Numeric Array:

These arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero.

Example
Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in function reference.
<html>
   <body>
   
      <?php
         /* First method to create array. */
         $numbers = array( 1, 2, 3, 4, 5);
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
         
         /* Second method to create array. */
         $numbers[0] = "one";
         $numbers[1] = "two";
         $numbers[2] = "three";
         $numbers[3] = "four";
         $numbers[4] = "five";
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
      ?>
      
   </body>
</html>

Associative Arrays:

The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.

NOTE − Don't keep associative array inside double quote while printing otherwise it would not return any value.

Example:
<html>
   <body>
      
      <?php
         /* First method to associate create array. */
         $salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
         
         echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
         echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
         echo "Salary of zara is ".  $salaries['zara']. "<br />";
         
         /* Second method to create array. */
         $salaries['mohammad'] = "high";
         $salaries['qadir'] = "medium";
         $salaries['zara'] = "low";
         
         echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
         echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
         echo "Salary of zara is ".  $salaries['zara']. "<br />";
      ?>
   
   </body>
</html>

Multidimensional Arrays:

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Example
In this example we create a two dimensional array to store marks of three students in three subjects −

This example is an associative array, you can create numeric array in the same fashion.
<html>
   <body>
      
      <?php
         $marks = array( 
            "mohammad" => array (
               "physics" => 35,
               "maths" => 30,
               "chemistry" => 39
            ),
            
            "qadir" => array (
               "physics" => 30,
               "maths" => 32,
               "chemistry" => 29
            ),
            
            "zara" => array (
               "physics" => 31,
               "maths" => 22,
               "chemistry" => 39
            )
         );
         
         /* Accessing multi-dimensional array values */
         echo "Marks for mohammad in physics : " ;
         echo $marks['mohammad']['physics'] . "<br />"; 
         
         echo "Marks for qadir in maths : ";
         echo $marks['qadir']['maths'] . "<br />"; 
         
         echo "Marks for zara in chemistry : " ;
         echo $marks['zara']['chemistry'] . "<br />"; 
      ?>
   
   </body>
</html>

Q11 Write all the shorting method of the array with example and defination.
Ans: What is sorting?
Sorting refers to ordering data in an alphabetical, numerical order and increasing or decreasing fashion according to some linear relationship among the data items.Sorting greatly improves the efficiency of searching.

Sorting Functions For Arrays In PHP

  • sort() – sorts arrays in ascending order
  • rsort() – sorts arrays in descending order
  • asort() – sorts associative arrays in ascending order, according to the value
  • ksort() – sorts associative arrays in ascending order, according to the key
  • arsort() – sorts associative arrays in descending order, according to the value
  • krsort() – sorts associative arrays in descending order, according to the key
(i).Sort Array in Ascending Order – sort():
The following function sorts the elements of a numerical array in ascending numerical order:
<!DOCTYPE html> 
<html> 
<body> 
  
<?php 
$numbers = array(40, 61, 2, 22, 13); 
sort($numbers); 
  
$arrlength = count($numbers); 
for($x = 0; $x < $arrlength; $x++) { 
    echo $numbers[$x]; 
    echo "<br>"; 
?> 
  
</body> 
</html> 
(ii). Sort Array in Descending Order – rsort()
The following function sorts the elements of a numerical array in descending numerical order:

<!DOCTYPE html> 
<html> 
<body> 
  
<?php 
$numbers = array(40, 61, 2, 22, 13); 
rsort($numbers); 
  
$arrlength = count($numbers); 
for($x = 0; $x < $arrlength; $x++) { 
    echo $numbers[$x]; 
    echo "<br>"; 
?> 
  
</body> 
</html> 

(iii). Sort Array in Ascending Order,According to Value – asort()
The following function sorts an associative array in ascending order, according to the value:

<!DOCTYPE html> 
<html> 
<body> 
  
<?php 
$age = array("ayush"=>"23", "shankar"=>"47", "kailash"=>"41"); 
asort($age); 
  
foreach($age as $x => $x_value) { 
    echo "Key=" . $x . ", Value=" . $x_value; 
    echo "<br>"; 
?> 
  
</body> 
</html> 

(iv). Sort Array in Ascending Order, According to Key – ksort()
The following function sorts an associative array in ascending order, according to the key:

<!DOCTYPE html> 
<html> 
<body> 
  
<?php 
$age = array("ayush"=>"23", "shankar"=>"47", "kailash"=>"41"); 
ksort($age); 
  
foreach($age as $x => $x_value) { 
    echo "Key=" . $x . ", Value=" . $x_value; 
    echo "<br>"; 
?> 
  
</body> 
</html> 

(v). Sort Array in Descending Order, According to Value – arsort()
The following function sorts an associative array in descending order, according to the value.

<!DOCTYPE html> 
<html> 
<body> 
  
<?php 
$age = array("ayush"=>"23", "shankar"=>"47", "kailash"=>"41"); 
arsort($age); 
  
foreach($age as $x => $x_value) { 
    echo "Key=" . $x . ", Value=" . $x_value; 
    echo "<br>"; 
?> 
  
</body> 
</html>

(vi). Sort Array in Descending Order, According to Key – krsort()
The following function sorts an associative array in descending order, according to the key.
<!DOCTYPE html> 
<html> 
<body> 
  
<?php 
$age = array("ayush"=>"23", "shankar"=>"47", "kailash"=>"41"); 
krsort($age); 
  
foreach($age as $x => $x_value) { 
    echo "Key=" . $x . ", Value=" . $x_value; 
    echo "<br>"; 
?> 
  
</body> 
</html> 

Q12. What is operator? explain all the types of operator.

Q13. What is string? explain any three string function with example.
Ans: PHP | Strings

Strings can be seen as a stream of characters. For example, ‘S’ is a character and ‘secretmind’ is a string. We have learned about basics of string data type in PHP. In this article we will discuss about strings in details. Every thing inside quotes , single (‘ ‘) and double (” “) in PHP is treated as a string.

1.strtoupper() function in PHP:
This function takes a string as argument and returns the string with all characters in Upper Case.
Syntax:

strtoupper($string)

Program to illustrate the use of strtoupper() function:

<?php 
# PHP code to convert to Upper Case 
function toUpper($string){ 
    return(strtoupper($string)); 
  
// Driver Code 
$string="GeeksforGeeks";   
echo (toUpper($string)); 
?>   

2.strtolower() function in PHP:

This function takes a string as argument ans returns the string with all of the characters in Lower Case.

Syntax:

strtolower($string)

example: 
<?php 
# PHP code to convert to Lower Case 
function toLower($string){ 
    return(strtolower($string)); 
  
// Driver Code 
$string="GeeksforGeeks";   
echo (toLower($string)); 
?>

3.ucfirst() function in PHP

This function takes a string as argument and returns the string with the first character in Upper Case and all other cases of the characters remains unchanged.
Syntax:

ucfirst($string)

Example:

<?php 
# PHP code to convert the first letter to Upper Case 
function firstUpper($string){ 
    return(ucfirst($string)); 
  
// Driver Code 
$string="welcome to GeeksforGeeks";   
echo (firstUpper($string)); 
?> 

Q14. What is data type in php ? explain all the data type.

Ans: Data Types in PHP:

The values assigned to a PHP variable may be of different data types including simple string and numeric types to more complex data types like arrays and objects.

PHP supports total eight primitive data types: Integer, Floating point number or Float, String, Booleans, Array, Object, resource and NULL. These data types are used to construct variables. Now let's discuss each one of them in detail.

1.PHP Integers
Integers are whole numbers, without a decimal point (..., -2, -1, 0, 1, 2, ...). Integers can be specified in decimal (base 10), hexadecimal (base 16 - prefixed with 0x) or octal (base 8 - prefixed with 0) notation, optionally preceded by a sign (- or +).

2.PHP Strings
Strings are sequences of characters, where every character is the same as a byte.

A string can hold letters, numbers, and special characters and it can be as large as up to 2GB (2147483647 bytes maximum). The simplest way to specify a string is to enclose it in single quotes (e.g. 'Hello world!'), however you can also use double quotes ("Hello world!").

3.PHP Floating Point Numbers or Doubles
Floating point numbers (also known as "floats", "doubles", or "real numbers") are decimal or fractional numbers, like demonstrated in the example below.
<?php
$a = 1.234;
var_dump($a);
echo "<br>";
$b = 10.2e3;
var_dump($b);
echo "<br>";
$c = 4E-10;
var_dump($c);
?>

4. PHP Booleans
Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).

5.PHP Objects
An object is a data type that not only allows storing data but also information on, how to process that data. An object is a specific instance of a class which serve as templates for objects. Objects are created based on this template via the new keyword.

Every object has properties and methods corresponding to those of its parent class. Every object instance is completely independent, with its own properties and methods, and can thus be manipulated independently of other objects of the same class.

6.PHP NULL
The special NULL value is used to represent empty variables in PHP. A variable of type NULL is a variable without any data. NULL is the only possible value of type null.

7.PHP Resources
A resource is a special variable, holding a reference to an external resource.

Resource variables typically hold special handlers to opened files and database connections.

8. PHP Arrays
An array is a variable that can hold more than one value at a time. It is useful to aggregate a series of related items together, for example a set of country or city names.

An array is formally defined as an indexed collection of data values. Each index (also known as the key) of an array is unique and references a corresponding value.

Q15. What do you mean by global and local scope of a variable.

الخميس، 2 يناير 2020

PHP Exam Paper || secret mind

PHP Exam Paper(part 1)




(any four)
(5+5+5)

Q1.shor notes (any three)
  • variables 
  • $server
  • Class
  • require

(8+7)
Q2.
A). Write a script to print 
           *
        *    *
      *    *   *
    *   *   *   *

B). Write a script to create a database with proper notification.
(8+7)
Q3.
A). What is file handling ? Explain any 5 attributes of file handling.
B). Write a program, to copy the content of a file into another file.
(8+7)
Q4.
A). Write difference between GET and POST.
B).Write a php script to get first name and last name from user and print it itno a new webpage.
(8+7)
Q5.
A). Write a PHP script to create a new table into a database.
B).Write a PHP scripte to insert a record into a table. 

Answer: 
Q1.A variable: 
Variable is nothing it is just name of the memory location. A Variable is simply a container i.e used to store both numeric and non-numeric information.

Rules for Variable declaration
  • Variables in PHP starts with a dollar($) sign, followed by the name of the variable.
  • The variable name must begin with a letter or the underscore character.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • A variable name should not contain space

Assigning Values to Variables
Assigning a value to a variable in PHP is quite east: use the equality(=) symbol, which also to the PHP's assignment operators.

This assign value on the right side of the equation to the variable on the left.

ex:
<?php

  $myCar = "Honda";

  echo $myCar;

?>


Answer Q1 B
$_SERVER :- $_SERVER is an array which holds information of headers, paths, script locations. Web server creates the entries in the array. This is not assured that every web server will provide similar information, rather some servers may include or exclude some information which are not listed here.

$_SERVER has following basic properties:

1. Set by web server.

2. Directly related to the runtime environment of the current php script.

3. It does the same job as $HTTP_SERVER_VARS used to do in previous versions of PHP

Answer Q1 D
The include() Function
The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.

Assume you want to create a common menu for your website. Then create a file menu.php with the following content.
<a href="http://www.secretmind.cf/index.htm">Home</a> - 
<a href="http://www.secretmind.cf/ebxml">ebXML</a> - 
<a href="http://www.secretmind.cf/ajax">AJAX</a> - 
<a href="http://www.secretmind.cf/perl">PERL</a> <br />

Now create as many pages as you like and include this file to create header. For example now your test.php file can have following content.

<html>
   <body>
   
      <?php include("menu.php"); ?>
      <p>This is an example to show how to include PHP file!</p>
      
   </body>
</html>

Answer Q2.
<?php
echo "<pre>";
$space = 10;
for ($i = 0; $i <= 10; $i++) {
     
    for ($k = 0; $k < $space; $k++) {
        echo "&nbsp;";
    }
    for ($j = 0; $j < 2 * $i - 1; $j++) {
        echo "*";
    }
     
    $space--;
    echo "<br/>";
}
echo "</pre>";
?>

 Answer Q2 B
<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
    echo "Database created successfully";
} else {
    echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

coming soon............



PHP Exam Paper(part 2)
(any four)
(8+7)
Q1. 
A) Write difference between GET  and POST.
B). What is loop ? Explain different types of loops use in php.
(8+7)
Q2.
A). write  a script to print Fibonacci series from 20 to 95.
B). Write  a script to check the given strings in palindrome or not (example: mom after reverse mom)
(8+7)
Q3 
A) What is Array/ Explain the syntax with example.
B) what is file handling ? Write a program to show all the content of "result.txt" on console.
(8+7)
Q4
A). What is SQLs ?
B). Write a script to connect with the server and create a database name "studentdatabase".
(5+5+5)
Q5
A) write difference between.(any three)
  • FTP and HTTP
  • Array and variable
  • Include and require
  • echo and print
  • 1
  • 2
  • 3
  • 4
  • 5




  • الاثنين، 30 ديسمبر 2019

    PHP tutorial part 2

    PHP TUTORIAL (part 2)

    aman gupta

    Comments in PHP

    // it is a single line comment 

    /* it is a multipul line comments*/


    About Variables in PHP

    Variables in a program are used to store some values or data that can be used later in a program. PHP has its own way of declaring and storing variables.variables are containers which is used to store information.some points are given below:

    1. you don't need to bother about data type of the variable.
    2. Every variable name will start by $ sign. Ex. $variable_Secretmind
    3. Name of the variable must be start from alphabet not from the numbers.
    4. you can't give space in variable name.
    5. you can't use keywords as a variable name.
    example:

    <?php
    $x=5;
    $y=5;

    $z= $x+$y;

    echo "Answer is $z";
    ?>

    Variable Scopes

    Scope of a variable is defined as its extent in program within which it can be accessed, i.e. the scope of a variable is the portion of the program with in which it is visible or can be accessed.

    Depending on the scopes, PHP has three variable scopes:


    1.Local variables: The variables declared within a function are called local variables to that function and has its scope only in that particular function. In simple words it cannot be accessed outside that function. Any declaration of a variable outside the function with same name as that of the one within the function is a complete different variable. We will learn about functions in details in later articles. For now consider a function as a block of statements.

    Example:

    <?php
    $x=4;
    function aman(){
    $x=0;
    print("inside function value of x is $x");

    }
    aman();
    print("outside function value is $x");
    ?>
    2.Global variables: The variables declared outside a function are called global variables. These variables can be accessed directly outside a function. To get access within a function we need to use the “global” keyword before the variable to refer to the global variable.
    Example:
    <?php
    $x=4;
    function aman(){
    GLOBAL $x;
    print("inside function value of x is $x");

    }
    aman();
    print("outside function value is $x");
    ?>
    3.Static variable: It is the characteristic of PHP to delete the variable, ones it completes its execution and the memory is freed. But sometimes we need to store the variables even after the completion of function execution. To do this we use static keyword and the variables are then called as static variables.
    Example:

    <?php 
    // function to demonstrate static variables 
    function static_var() 
    {    
        // static variable 
        static $num = 5; 
        $sum = 2;   
        $sum++; 
        $num++; 
        echo $num, "\n"; 
        echo $sum, "\n"; 
    // first function call 
    static_var(); 
    // second function call 
    static_var(); 
    ?> 

    Basic Types of Operators in PHP

    Operators are symbols that tell the PHP processor to perform certain actions. For example, the addition (+) symbol is an operator that tells PHP to add two variables or values, while the greater-than (>) symbol is an operator that tells PHP to compare two values.Operators are used to perform operations on variables and values.PHP divides the operators in the following groups:

    1. Concatenation Operators( . )
    2. Arithmetic Operators ( +, - , / , * , %)
    3. Assignment Operators( = )
    4. Increment/Decrement Operators( ++ , -- )
    5. Comparison Operators( == ,=== , < , > , <= , >= )

    Question 
    1.Different between  global variable and static variable .
    2.What is the super global variable ? And describe all parts of super global variable.
    3.Describe 3 variable scope.
    4. What is operators in PHP ? Describe Assignment or increment/ Decrement operators.


    السبت، 28 ديسمبر 2019

    mysql database with php

    mysql database with php





    1.Create database with php

    Open a Connection to MySQL

    Before we can access data in the MySQL database, we need to be able to connect to the server:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";


    // Create connection
    $conn = new mysqli($servername, $username, $password);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    echo "connection succesfully";

    $conn->close();

    ?>


    2.Create a database:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";


    // Create connection
    $conn = new mysqli($servername,$username,$password);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "Create DATABASE demo";

    if ($conn->query($sql) === TRUE) {
        echo "database has been cerated";
    } else {
      echo "database has been not craeted".$conn->connect_error;
    }

    $conn->close();

    ?>

    3. Create table with php:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "demo";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // sql to create table
    $sql = "CREATE TABLE aman (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )";

    if ($conn->query($sql) === TRUE) {
        echo "Table aman created successfully";
    } else {
        echo "Error creating table: " . $conn->error;
    }
    $conn->close();
    ?>

    4. Insert single line data with php:
    <?php
    $servername = "localhost";
    $username = "root";
    $password = "p";
    $dbname = "demo";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection

    if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
    }
    $sql = "INSERT INTO aman (firstname, lastname, email)

    VALUES ('Aman', 'Gupta', 'gaman5088@gmail.com')";
    if ($conn->query($sql) === TRUE) {

        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    $conn->close();
    ?>

    insert multiple data in database with php:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "demo";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql = "INSERT INTO aman (firstname, lastname, email)
    VALUES ('varun', 'meena', 'varun@example.com');";
    $sql .= "INSERT INTO aman (firstname, lastname, email)
    VALUES ('vandita', 'rajput', 'vandita@example.com');";
    $sql .= "INSERT INTO aman (firstname, lastname, email)
    VALUES ('shubham', 'podder', 'shubham@example.com')";
    if ($conn->multi_query($sql) === TRUE) {
        echo "New records created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    $conn->close();
    ?>

    output:-

    Aman gupta

    6.PHP MySQL Select Data:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "demo";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT id, firstname, lastname FROM aman";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
        }
    } else {
        echo "0 results";
    }
    $conn->close();
    ?>

    output:-




    7. Insert data in database from html form:
    <!DOCTYPE html>
    <html>
    <head>
    <title>form </title>
    </head>
    <body>
    <form action="" method="POST">

    fName:
    <input type="text" name="name">
    <br><br>
    lname <input type="text" name="lname"><br><br>

    Email:<input type="Email" name="Email"><br><br>
    <input type="submit" name="submit">
    </form>
    <?php
    $ser="localhost";
    $user="root";
    $pass ="";
    $dbname="demo";

    $cn = new mysqli($ser,$user,$pass,$dbname);

    if ($cn->connect_error) {

    die("connection failed".$connect_error);
    }
    $sql = "INSERT INTO aman ( firstname,lastname,email) VALUES ('".$_POST["name"]."','".$_POST["lname"]."','".$_POST["Email"]."')";

    if ($cn->query($sql)=== TRUE) {

       echo"<script> alert('new record enter successfylly');</script>";
    # code...
    }else
    {
    echo "<script>alert('error:".$sql."<br>".$cn->error."');</script>";
    }
    $cn->close();
     ?>
    </body>
    </html>


    output:





    الأحد، 22 ديسمبر 2019

    PHP Important Qenstions For Exam

    PHP Important Questions For Exam


    Secret MInd

    1.What is the difference between echo and print with examples.
    Ans:-
    echo:- 

    1. echo statement is used to display the output. echo can be used with parentheses or without parentheses.
    2. We can pass multiple strings with echo and all of these must separate with commas(,).
    3. echo doesn’t return any value.
    4. When we print with echo, the operation is fast as compared to print.
    Examples:
     <?php
    $name="Abhi";
    echo $name;
    //or
    echo ($name);
    ?>

    print:- 

    1. print statement is used to display the output. print can be used with parentheses or without parentheses.
    2. using print can doesn’t pass multiple arguments
    3. print always return 1
    4. When we print with print, the operation is slow as compared to echo.


    Example:
    <?php
    $name="Abhi";
    print $name;
    //or
    print ($name);
    ?>

    2. Different between $_GET and $_POST briefly.
    Ans:- Using the GET and POST methods, the browser client can send data to the web server. In PHP the GET and POST methods are used to retrieve information from forms, such as user input. Get and Post are methods used to send data to the server. These methods are used for data handling in forms.  Where each method varies a little in the way they work.

    $_GET:-
    In the GET method, we can also send data to the server. But when using the GET method we can't send the login details with a word because it is less secure (information sent from a form with the GET method is visible to everyone). We can say that the GET method is for getting something from the server; it doesn't mean that you cannot send a parameter to the server.
    The main points about the GET method are as follows:

    • The GET method is used to collect values in a form.
    • GET method is used when the URL is sent to the server.
    • GET method has limits on the amount of information to send because URL lengths are limited.
    • The Get method is used to retrieve web pages from the server.
    • The GET method is the default method for many browsers.
    • Data is sent as a part of the URL in 'name-value' pairs.
    • In the GET method page and the encoded information are separated by the question mark  (?) sign.
    • In the GET method, the browser appends the data onto the URL.
    • The Get method is less secure because information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) .
    • GET can't be used to send binary data, like images or word documents, to the server.
    Example:-
    First of all we create a PHP file which is called by the HTML page in later.

    <html>
    <body bgcolor="pink">
    Welcome <?php echo $_GET ["Name"]; ?>.<br/>
    You are <?php echo $_GET ["Class"]; ?> Qualified !!
    </body>
    </html>

    The above file is to be saved with the name "get.php", which is called by the HTML page later.

    <html>
    <body bgcolor="pink"><table>
    <form action="get.php" method="get">
    <tr><td>Name: <input type="text" name="Name" /></td></tr>
    <tr><td>Class : <input type="text" name="Class" /></td></tr>
    <input type="submit" " value="Submit"/>
    </form>
    </body>
    </html>

     $_POST:-
    In PHP $_POST variable is used to collect values from a form sent with method="post". In the POST method one can request as well as send some data to the server. The POST method is used when one can send a long enquiry form. Using the POST method the login details with word can be posted because it is secure (information sent from a form with the POST method is invisible to everyone).

    The main points about POST method are as follows:

    • The POST method is used to collect values from a form.
    • The POST method has no limits on the amount of information to send because URL lengths are unlimited.
    • The POST method is the not default method for many browsers.
    • In the POST method, the page and the encoded information are not separated by the question mark  (?) sign.
    • In the POST method, the browser doesn't append the data onto the URL.
    • The POST method is secure because information sent from a form with the GET method is invisible to everyone.
    • The POST method can be used to send binary data, like images or Word documents, to the server.
    • In the POST method, the data is sent as standard input.
    • The POST method is slower than the GET method.
    • PHP provides the $_POST associative array to access all the information sent using the GET method.
    Example:-

    First of all we create a PHP file which is called by the HTML page later.

    <html>
    <body bgcolor="pink">
    Welcome <?php echo $_POST ["Name"]; ?>.<br/>
    You are <?php echo $_POST ["Class"]; ?> Qualified !!
    </body>
    </html>

    The above file is saved with the "post.php" name, which is called by the HTML page later.

    <html>
    <body bgcolor="pink">
    <table>
    <form action="post.php" method="post">
    <tr><td>Name: <input type="text" name="Name" /></td></tr>
    <tr><td>Class : <input type="text" name="Class" /></td></tr>
    <input type="submit" " value="Submit"/>
    </form>
    </body>
    </html>

    This file is saved as "post.html".

    3.What are super-global variable? Explain All.
    Ans:- Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
    The PHP superglobal variables are:
    • $GLOBALS
    • $_SERVER
    • $_REQUEST
    • $_POST
    • $_GET
    • $_FILES
    • $_ENV
    • $_COOKIE
    • $_SESSION
    1.$GLOBALS:-  $GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods).

    PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

    The example below shows how to use the super global variable $GLOBALS
    <?php
    $x = 75;
    $y = 25;
    function addition() {
        $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
    }
    addition();
    echo $z;
    ?>
    2. $_SERVER:-  $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.

    The example below shows how to use some of the elements in $_SERVER:
    <?php
    echo $_SERVER['PHP_SELF'];
    echo "<br>";
    echo $_SERVER['SERVER_NAME'];
    echo "<br>";
    echo $_SERVER['HTTP_HOST'];
    echo "<br>";
    echo $_SERVER['HTTP_REFERER'];
    echo "<br>";
    echo $_SERVER['HTTP_USER_AGENT'];
    echo "<br>";
    echo $_SERVER['SCRIPT_NAME'];
    ?>

    3.$_REQUEST:-  PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting an HTML form.

    The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we point to this file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_REQUEST to collect the value of the input field:
    <html>
    <body>

    <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
      Name: <input type="text" name="fname">
      <input type="submit">
    </form>

    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // collect value of input field
        $name = $_REQUEST['fname'];
        if (empty($name)) {
            echo "Name is empty";
        } else {
            echo $name;
        }
    }
    ?>

    </body>
    </html>

    4. $_POST:- PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables.

    The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we point to the file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_POST to collect the value of the input field:
    <html>
    <body>

    <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
      Name: <input type="text" name="fname">
      <input type="submit">
    </form>

    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // collect value of input field
        $name = $_POST['fname'];
        if (empty($name)) {
            echo "Name is empty";
        } else {
            echo $name;
        }
    }
    ?>

    </body>
    </html>

    5.$_GET:- PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get".

    $_GET can also collect data sent in the URL.

    Assume we have an HTML page that contains a hyperlink with parameters:

    <html>
    <body>

    <a href="test_get.php?subject=PHP&web=Secretmind.cf">Test $GET</a>

    </body>
    </html>
    When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to "test_get.php", and you can then access their values in "test_get.php" with $_GET.

    The example below shows the code in "test_get.php":
    <html>
    <body>

    <?php
    echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
    ?>

    </body>
    </html>

    6.$_FILES:- $_FILES is a super global variable which can be used to upload files. Here we will see an example in which our php script checks if the form to upload the file is being submitted and generates a message if true.

    Here is the html code (upload.php):
    <html>
    <body>
    <form action="upload_file.php" method="post"
    enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file" />
    <br />
    <input type="submit" name="submit" value="Submit" />
    </form>
    </body>
    </html>

    Code of files.php file:

    <?php
    if ($_FILES["file"] > 0)
      {
      echo "You have selected a file to upload";
      }
    ?>

    7.$_ENV:- $_ENV is used to return the environment variables from the web server.
    <?php
    echo $_ENV['username'];
    ?>

    8.$_COOKIE:- Cookies are small text files loaded from a server to a client computer storing some information regarding the client computer, so that when the same page from the server is visited by the user, necessary information can be collected from the cookie itself, decreasing the latency to open the page.

    $_COOKIE retrieves those cookies.

    <?php
    setrawcookie();
    print_r($_COOKIE);
    ?>

    9.$_SESSION:- Sessions are wonderful ways to pass variables. All you need to do is start a session by session_start();Then all the variables you store within a $_SESSION, you can access it from anywhere on the server. Here is an example:  

    Example of $_SESSION

    <?php
    session_start();
    $_SESSION['Secretmind']='The largest online tutorial';
    echo $_SESSION['Secretmind'];
    ?>

    4.What are the differences between session and cookie?
    Ans:
    The session is a global variable which is used in the server to store the session data. When a new session creates the cookie with the session id is stored on the visitor's computer. The session variable can store more data than the cookie variable.

    Session data are stored in a $_SESSION array and Cookie data are stored in a $_COOKIE array. Session values are removed automatically when the visitor closes the browser and cookie values are not removed automatically.

    5.Which functions are used to remove whitespaces from the string?
    Ans: There are three functions in PHP to remove the whitespaces from the string.

    trim() – It removes whitespaces from the left and right side of the string.
    ltrim() – It removes whitespaces from the from the left side of the string.
    rtrim() – It removes whitespaces from the from the right side of the string.

    6.what is PHP array ? And what are the different between Index array and associative array?
    Ans: A PHP array is a variable that stores more than one piece of related data in a single variable.

    Index array
    There are two ways to create indexed arrays.

    • first way to use array() function without any index, index are assigned automatically starting from 0.
    • second way to manually assign index and create the array.


    PHP count() function is used to get the length of an array. We can use for loop to loop through all the values of an indexed array.

    Below code shows both the ways to create an indexed array and loop through them in PHP.

    <?php
    $colors = array("Red","Green","Blue");

    $colors1[0] = "Red";
    $colors1[1] = "Green";

    $length = count($colors);
    echo "colors array length=" . $length; // prints "colors array length=3"
    echo "<br>";
    echo "colors1 array length=" . count($colors1); // prints "colors1 array length=2"

    //looping an indexed array
    for($i=0; $i<$length; $i++){
    echo $colors[$i];
    echo "<br>";
    }
    ?>

    Associative array
    Associative arrays uses named keys for values and we can create them in similar way like indexed arrays. foreach is used to loop through an associative array.


    <?php

    $colors = array("0"=>"Red","1"=>"Green","2"=>"Blue");

    echo "0th element of array is " . $colors["0"];
    echo "<br>";
    //looping
    foreach ($colors as $key=>$value){
    echo "Key=".$key." value=".$value;
    echo "<br>";
    }
    ?> 

    7.What is cookie? Expain creation, modification and distrotion(Expiration of cookie).
    Ans: Cookies are small text files loaded from a server to a client computer storing some information regarding the client computer, so that when the same page from the server is visited by the user, necessary information can be collected from the cookie itself, decreasing the latency to open the page.

    PHP create or retrieve a cookie:-
    The following example creates a cookie name "user" with the value "Aman".
    The cookie will expire after 30 days(86400*30).The "/" means that the cookie is available in the entire website.
    Than we retrieve the value of the cookie "user" (using the GLOBAL variable $COOKIE).Be also use the isset() function to find out it the cookies set.

    <!DOCTYPE html>
    <?php
    $cookie_name = "user";
    $cookie_value = "Aman Gupta";
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
    ?>
    <html>
    <body>

    <?php
    if(!isset($_COOKIE[$cookie_name])) {
         echo "Cookie named '" . $cookie_name . "' is not set!";
    } else {
         echo "Cookie '" . $cookie_name . "' is set!<br>";
         echo "Value is: " . $_COOKIE[$cookie_name];
    }
    ?>

    <p><strong>Note:</strong> You might have to reload the page to see the value of the cookie.</p>

    </body>
    </html>



    Modify a Cookie Value:
    To modify a cookie, just set (again) the cookie using the setcookie() function:

    Example
    <?php
    $cookie_name = "user";
    $cookie_value = "Alex Porter";
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
    ?>
    <html>
    <body>

    <?php
    if(!isset($_COOKIE[$cookie_name])) {
        echo "Cookie named '" . $cookie_name . "' is not set!";
    } else {
        echo "Cookie '" . $cookie_name . "' is set!<br>";
        echo "Value is: " . $_COOKIE[$cookie_name];
    }
    ?>

    </body>
    </html>

    Delete a Cookie:
    To delete a cookie, use the setcookie() function with an expiration date in the past:

    Example
    <?php
    // set the expiration date to one hour ago
    setcookie("user", "", time() - 3600);
    ?>
    <html>
    <body>

    <?php
    echo "Cookie 'user' is deleted.";
    ?>

    </body>
    </html>

    8.What is session ? Explain briefly it's start to end.
    Ans:  When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.

    Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.

    So; Session variables hold information about one single user, and are available to all pages in one application.

    start a PHP Session:

    A session is started with the session_start() function.

    Session variables are set with the PHP global variable: $_SESSION.

    Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and set some session variables:

    Example
    <?php
    session_start();
    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <title></title>
    </head>
    <body>
    <?php
    $_SESSION["favcolor"]="red";
    $_SESSION["facanimal"]="cat";
    echo "session variable are set";
    ?>
    </body>
    </html>

    Start a PHP Session:
    A session is started with the session_start() function.

    Session variables are set with the PHP global variable: $_SESSION.

    Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and set some session variables:

    Example
    <?php
    // Start the session
    session_start();
    ?>
    <!DOCTYPE html>
    <html>
    <body>

    <?php
    // Set session variables
    $_SESSION["favcolor"] = "green";
    $_SESSION["favanimal"] = "cat";
    echo "Session variables are set.";
    ?>

    </body>
    </html>

    9.Different between scripting and programming languages.
    Ans:
    Scripting language:-

    Scripting languages, as the name suggests, is a programming language that supports scripts. A scripting language binds a set of software components that collaborate to solve a particular problem. Scripting assumes the existence of powerful components and provides the means to connect them together. Scripting languages are glue languages that integrate the execution of system utilities including compilers; command line interpretation; shell-based programming; and execution of codes written in web-based languages. The purpose of a scripting language is the development of applications by plugging existing components together and they generally favor high-level programming over execution speed. Scripting is used in a variety of applications, and scripting languages are correspondingly diverse. Python is a powerful scripting language for complex system involving operating system, networks, and web-based programming.

    programming language:-

    A programming language is an organized way of communicating with a computer, such that the computer behaves according to the instructions given by the programmer. A programming language is an artificial formalism in which algorithms can be expressed. In the modern era, the problems to be solved by computers lie in different problem domains such as scientific computing, database programming, business applications, process automation, and web-based applications. All these domains are quite different with varied requirements. A programming language is a specific set of instructions given to a computer in a language that the computer understands to perform specific tasks. Today’s programming languages are the product of development that started in the 1950s. The term programming languages usually refer to high-level languages such as C++, Java, Ada, Pascal, and FORTRAN.

    Aman gupta


    10.What do you mean by procedural programming structure and object oriented programming structure ?
    Ans:
    Aman gupta

    11.Explain include and require with example.
    Ans:-
    INCLUDE()REQUIRE()
    include() function takes one argument , a path/name of the specified file you want to include.require() function performs the similar functionality as include() function, takes one argument i.e. path/name of the file you want to include.
    Syntax :
    include(File-name);
    Example :
    include (“header.php”).
    Syntax :
    require(File-name);
    Example :
    require(“header.php”);
    include() function does not stop execution , just give warning and continues to execute the script in case of file name not found i..e missing/misnamed files .require() function gives fatal error if it founds any problem like file not found or misnamed files and stops the execution once get fatal error.
    include() function can be used in loops or control structure.require() function can not be used in loops or control structures.
    You can return a value from an included file
    Ex:
    $result = include ‘rtnvalue.php’;
    File included as the result of a require statement cannot return a value.
    You can use include when file is not required or not so important .When file is required by the script, better to use require() instead of include().
    The include() function:

    This function is used to copy all the contents of a file called within the function, text wise into a file from which it is called. This happens before the server exceutes the code. Example:
    Lets have a file called even.php with the following code:

    <?php 
    // file to be included 
    echo "Hello Secret mind"
    ?> 

    Now let us try to include this file into another php file index.php file. We will see that the contents of both the file are shown.

    <?php  
        include("even.php"); 
        echo "<br>Above File is Included"
    ?> 

    The require() function:

    The require() function performs same as the include() function. It also takes the file that is required and copies the whole code into the file from where the require() function is called. There is a single difference between the include() and require() function which we will see following this example:
    Lets have a file called even.php with the following code:
    <?php 
    // file to be included 
    echo "Hello GeeksforGeeks"
    ?> 

    Now if we try to include this file using require() function this file into a web page we need to use a index.php file. We will see that the contents of both the file are shown.

    <?php  
        require("even.php"); 
        echo "<br>Above File is Required"
    ?> 


    12.Write a program of form validation from server site scripting.
    Ans:
    <!DOCTYPE HTML>  
    <html>
    <head>
    <style>
    .error {color: #FF0000;}
    </style>
    </head>
    <body>  

    <?php
    // define variables and set to empty values
    $nameErr = $emailErr = $genderErr = $websiteErr = "";
    $name = $email = $gender = $comment = $website = "";

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["name"])) {
        $nameErr = "Name is required";
      } else {
        $name = test_input($_POST["name"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
          $nameErr = "Only letters and white space allowed";
        }
      }
      
      if (empty($_POST["email"])) {
        $emailErr = "Email is required";
      } else {
        $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $emailErr = "Invalid email format";
        }
      }
        
      if (empty($_POST["website"])) {
        $website = "";
      } else {
        $website = test_input($_POST["website"]);
        // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
          $websiteErr = "Invalid URL";
        }
      }

      if (empty($_POST["comment"])) {
        $comment = "";
      } else {
        $comment = test_input($_POST["comment"]);
      }

      if (empty($_POST["gender"])) {
        $genderErr = "Gender is required";
      } else {
        $gender = test_input($_POST["gender"]);
      }
    }

    function test_input($data) {
      $data = trim($data);
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
      return $data;
    }
    ?>

    <h2>PHP Form Validation Example</h2>
    <p><span class="error">* required field</span></p>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
      Name: <input type="text" name="name" value="<?php echo $name;?>">
      <span class="error">* <?php echo $nameErr;?></span>
      <br><br>
      E-mail: <input type="text" name="email" value="<?php echo $email;?>">
      <span class="error">* <?php echo $emailErr;?></span>
      <br><br>
      Website: <input type="text" name="website" value="<?php echo $website;?>">
      <span class="error"><?php echo $websiteErr;?></span>
      <br><br>
      Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
      <br><br>
      Gender:
      <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
      <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
      <input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other  
      <span class="error">* <?php echo $genderErr;?></span>
      <br><br>
      <input type="submit" name="submit" value="Submit">  
    </form>

    <?php
    echo "<h2>Your Input:</h2>";
    echo $name;
    echo "<br>";
    echo $email;
    echo "<br>";
    echo $website;
    echo "<br>";
    echo $comment;
    echo "<br>";
    echo $gender;
    ?>

    </body>
    </html>


    13. Different between == and === .
    Ans: Coming soon.





     

  • 1
  • 2
  • 3
  • 4
  • 5