PHP | Important Questions and Functions

# Improve Database Transaction performance in SQL server

1. Use Indexes:

  Indexes act like internal guides for the database to locate specific information quickly. Identify frequently used columns in WHERE clauses, JOIN conditions, and ORDER BY clauses, and create indexes on those columns. However, creating too many indexes can slow down adding and updating data, so use them strategically.
Understanding the Need for Indexes
Indexes are crucial for optimizing database query performance, especially for large datasets. They create a searchable structure within a table, allowing the database to quickly locate specific records based on indexed columns. However, over-indexing can negatively impact write operations (inserts, updates, deletes) as the index itself needs to be updated.

Identifying Columns for Indexing
Before creating indexes, carefully analyze your application's query patterns. Focus on columns frequently used in:

  • WHERE clauses: Columns used to filter data.
  • ORDER BY clauses: Columns used to sort results.
  • GROUP BY clauses: Columns used to group data.
  • JOIN conditions: Columns involved in table relationships.

2. Use Select instead of Select *

Select * from GeeksforGeeks; – Gives you the complete table as an output whereas 
Select condition from GeeksforGeeks; –  Gives you only the preferred(selected) value

# PHP File Handling

PHP Manipulating Files
PHP has several functions for creating, reading, uploading, and editing files.

<?php
echo readfile("webdictionary.txt");
?>

<?php
$myfile = fopen("webdictionary.txt""r"or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>

open files is with the fopen() function
The fread() function reads from an open file.
The fclose() function is used to close an open file.
The fgets() function is used to read a single line from a file.
The fwrite() function is used to write to a file.


# PHP File Upload

First, ensure that PHP is configured to allow file uploads.

In your "php.ini" file, search for the file_uploads directive, and set it to On:

file_uploads = On


then,

<form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
</form>

// File details 
$file_name = $_FILES['file']['name']; 
$file_size = $_FILES['file']['size']; 
$file_tmp = $_FILES['file']['tmp_name']; 
$file_type = $_FILES['file']['type']; 
$file_error = $_FILES['file']['error'];

move_uploaded_file($file_tmp, $upload_dir . $file_name)

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}


// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

1. Uploading File
move_uploaded_file($file_tmp$upload_dir . $file_name)
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)

require('helper.php');

if(isset($_POST['submit'])){
    $file = $_FILES['file'];
    if(isset($file) && $file['error'] == 0){
        $filename       = $file['name'];
        $fileTempName   = $file['tmp_name'];
        $fileSize       = $file['size'];
        $fileType       = $file['type'];
        $extention      = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        $path           = "uploads/";
        $rendomString   = getRandomString(64);
        $newFilename    = $rendomString.time().".".$extention;
        $upload_path    = $path.$newFilename;
        //create directory if available available
        if(!is_dir($path)){
            mkdir($path, 0775, true);
        }
        move_uploaded_file($fileTempName, $upload_path);
        echo "File uploaded successfullly";
    }else{
        echo "file not uploaded";
    }
}




2. File Move
$old_file = "path/to/oldfile.txt";
$new_file = "path/to/newfile.txt";

rename($old_file, $new_file);

3. File Delete
$file_to_delete = "path/to/file_to_delete.txt";

unlink($file_to_delete);

4. File Read

$file = "path/to/file.txt";
$file_content = file_get_contents($file); 
echo $file_content;

5. File Write

$file = "path/to/file.txt";
$data = "Hello, world!";
file_put_contents($file, $data);

6. if File Exists

$file = "path/to/file.txt";

if (file_exists($file)) {
    echo "File exists.";
}

7. File Size:

$file = "path/to/file.txt";
$file_size = filesize($file);

# Cookie

setcookie(name, value, expire, path, domain, secure, httponly);
  • name: The name of the cookie.
  • value: The value of the cookie.
  • expire: (Optional) The expiration time of the cookie. If not set, the cookie will expire when the session ends.
  • path: (Optional) The path on the server for which the cookie will be available.
  • domain: (Optional) The domain for which the cookie is available.
  • secure: (Optional) Indicates that the cookie should only be transmitted over a secure HTTPS connection.
  • httponly: (Optional) When set to true, the cookie will be accessible only through the HTTP protocol.
Set Cookie
setcookie("name", "Ram", time()+3600, "/");

Modifying a Cookie
setcookie("name""Shyam"time()+3600, "/");

Delete Cookie
// set the expiration date to one hour ago
setcookie("user""", time() - 3600);


# Types of Errors in PHP


Error is the fault or mistake in a program. It can be several types. Error can occur due to wrong syntax or wrong logic. It is a type of mistakes or condition of having incorrect knowledge of the code.

There are various types of errors in PHP but it contains basically four main type of errors.

1. Parse error or Syntax Error:

It is the type of error done by the programmer in the source code of the program. The syntax error is caught by the compiler. After fixing the syntax error the compiler compile the code and execute it. Parse errors can be caused dues to unclosed quotes, missing or Extra parentheses, Unclosed braces, Missing semicolon etc
Example:

<?php 
$x = "geeks"; 
y = "Computer science"; 
echo $x; 
echo $y; 
?> 

Error Example:
PHP Parse error:  syntax error, unexpected '=' 
in /home/18cb2875ac563160a6120819bab084c8.php on line 3

2. Fatal Error:

It is the type of error where PHP compiler understand the PHP code but it recognizes an undeclared function. This means that function is called without the definition of function.
Example:

<?php 
  
function add($x, $y) 
    $sum = $x + $y; 
    echo "sum = " . $sum; 
$x = 0; 
$y = 20; 
add($x, $y); 
  
diff($x, $y); 
?> 
Error:

PHP Fatal error:  
Uncaught Error: 
Call to undefined function diff() 
in /home/36db1ad4634ff7deb7f7347a4ac14d3a.php:12

Stack trace:
#0 {main}
  thrown in /home/36db1ad4634ff7deb7f7347a4ac14d3a.php on line 12

Explanation : In line 12, function is called but the definition of function is not available. So it gives error.

3. Warning Errors :

 The main reason of warning errors are including a missing file. This means that the PHP function call the missing file.
Example:

<?php  
  
$x = "GeeksforGeeks"; 
  
include ("gfg.php"); 
  
echo $x . "Computer science portal"; 
?> 
Error:

PHP Warning: include(gfg.php): failed to 
open stream: No such file or directory in 
/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5
PHP Warning:  include(): Failed opening 'gfg.php'
 for inclusion (include_path='.:/usr/share/php') in 
/home/aed0ed3b35fece41022f332aba5c9b45.php on line 5
Explanation: This program call an undefined file gfg.php which are not available. So it produces error.


4. Notice Error: 

It is similar to warning error. It means that the program contains something wrong but it allows the execution of script.
Example:

<?php  
  
$x = "GeeksforGeeks"; 
  
echo $x; 
  
echo $geeks; 
?> 
Error:

PHP Notice:  Undefined variable: geeks in 
/home/84c47fe936e1068b69fb834508d59689.php on line 5
Output:

GeeksforGeeks
Explanation: This program use undeclared variable $geeks so it gives error message.


# Difference between Include() and require()


include() and require() are functions in PHP used to incorporate the contents of one file into another during execution.

Differences between include() and require()

The primary difference lies in their behavior when the included file is not found:

include(): Generates a warning (E_WARNING) if the file is not found, but the script continues to execute.
require(): Generates a fatal error (E_COMPILE_ERROR) if the file is not found, and the script terminates.

When to use which
include(): Used when the included file is optional, and the script should continue even if it's missing. For example, including a file for additional features.
require(): Used when the included file is essential for the script's functionality. For example, including a database connection file.


# String functions


1. strlen() It returns the length of the string i.e. the count of all the characters in the string including whitespace characters. $str = "Hello World!"; echo strlen($str); // output= 12 2. strrev() It returns the reversed string of the given string. $str = "Hello World!"; echo strrev($str); //output= !dlroW olleH 3. strtoupper() and strtolower() It returns the string after changing the cases of its letters. strtoupper(): It returns the string after converting all the letters to uppercase. strtolower(): It returns the string after converting all the letters to lowercase. Example: $str = "GeeksForGeeks"; echo strtoupper($str); //output=GEEKSFORGEEKS echo strtolower($str); //output=geeksforgeeks 4. str_replace() It is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively. syntax: str_replace ( $searchVal, $replaceVal, $subjectVal, $count ); $count: This parameter is optional and if passed, its value will be set to the total number of replacement operations performed on the string $subjectVal. Example: $str = "Hello I am Manish Tiwari"; $output = str_replace('Manish', "Deelip",$str); echo $output; //Output= Hello I am Deelip Tiwari 5. explode() Break a string into an array $str = "Hello world."; print_r (explode(" ",$str)); //output= Array ( [0] => Hello [1] => world.) 6 strlen(): Returns the length of a string
7. echo(): Outputs one or more strings


# Array functions


1. array_push(): Inserts one or more elements to the end of an array
2. array_pop(): Deletes the last element of an array 3. array_merge($arr1, $arr2, $arr3,...): Merges one or more arrays into one array, and make one array. Example: $a1=array("red","green"); $a2=array("blue","yellow"); print_r(array_merge($a1,$a2)); Output: Array ( [0] => red [1] => green [2] => blue [3] => yellow ) 4. array_combine($arr1, $arr2): Creates an array by using the elements from one array as "keys" and second array as "values". Example: $array1 = array("subject1" ,"subject2"); $array2 = array( "PHP", "java"); $final = array_combine($array1, $array2); Output: Array ( [subject1] => PHP [subject2] => java ) 5. array_filter(): Filters the null values or values of an array using a callback function
example1: $a2=array(1,'',3,2,'',3,4,' '); print_r(array_filter($a2)); output: Array ( [0] => 1 [2] => 3 [3] => 2 [5] => 3 [6] => 4 [7] => ) example2: function get_odd($var){ if($var % 2 != 0){ return $var; } } $a1=array(1,3,2,3,4,7,6,5); print_r(array_filter($a1,"get_odd")); 6. array_diff(): Compare arrays, and returns the differences (compare values only not key) example: $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"green","g"=>"blue"); $result=array_diff($a1,$a2); print_r($result); //Array ( [d] => yellow ) 7. array_keys(): This function accepts a PHP array and returns a new array containing only its keys (not its values). 8. array_values(): This function accepts a PHP array and returns a new array containing only its values (not its keys). 9. array_reverse(): The function reverses the order of elements in an array. 10. array_search(): Searches an array for a given value and returns the key example: $a=array("a"=>"red","b"=>"green","c"=>"blue"); echo array_search("red",$a); //output: a 11. array_unique(): Removes duplicate values from an array example: $a=array("a"=>"red","b"=>"green","c"=>"red"); print_r(array_unique($a)); 12. in_array(): Checks if a specified value exists in an array $people = array("Peter", "Joe", "Glenn", "Cleveland"); if (in_array("Glenn", $people)) //function return boolean value 1 or null { echo "Match found"; } 13. sizeof()/count(): Return the number of elements in an array








Post a Comment

0 Comments

Visual Studio