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

Tuesday, January 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.

No comments:

Post a Comment

Please do not enter any spam link in the comment box.