PHP Question
1. Super Global Variables
Super global variables are variables that can be accessed from any part of a script, regardless of scope. They are automatically available in all functions and classes.
Examples of Super Global Variables:
2. Print vs. Echo
Both print
and echo
are used to output strings in PHP. However, there are some subtle differences:
print
: A language construct, used with parentheses.echo
: A language construct, can be used with or without parentheses.print
: Always returns 1.echo
: Doesn't return a value.print
: Can only take one argument.echo
: Can take multiple arguments, separated by commas.Example:
print("Hello, world!");
echo "Hello, world!";
echo "Hello", " ", "world!";
3. Magic Methods
Magic methods are special methods that are automatically called when certain operations are performed on an object.
Examples of Magic Methods:
Example:
class MyClass {
public function __construct() {
echo "Object created";
}
public function __destruct() {
echo "Object destroyed";
}
}
$obj = new MyClass();
4. Session and Cookie
5. Ways to Define a Constant
There are two ways to define a constant in PHP:
define()
function: PHP
define("PI", 3.14159);
const
keyword: PHP
class MyClass {
const MY_CONSTANT = "Hello";
}
6. Opening a File in PHP
To open a file in PHP, you use the fopen()
function. The second argument specifies the file mode, which determines how the file is opened:
Example:
$file = fopen("myfile.txt", "r");
7. Implode() vs. Explode()
Example:
$array = ["apple", "banana", "cherry"];
$string = implode(",", $array); // "apple,banana,cherry"
$string = "apple,banana,cherry";
$array = explode(",", $string); // ["apple", "banana", "cherry"]
8. Uploading Files in PHP
To upload files in PHP, you use the $_FILES
superglobal variable. You need to handle the file upload using form and server-side scripting.
Example:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if(isset($_POST["submit"])) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// 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;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
9. Using a Method Within a Class
To use the number()
method within the sum()
method of class A
, you can simply call it like any other method:
class A {
public function sum() {
$num = $this->number();
// Use $num in your sum calculation
}
public function diff() {
// ...
}
public function number() {
return 10;
}
}
10. $ vs. $∗∗∗∗∗: Represents a variable.
Example:
$a = "hello";
$$a = "world";
echo $hello; // Output: world
11. Magic Functions and Their Uses
Magic functions are special methods that are automatically called when certain operations are performed on an object. They are used to customize object behavior.
Examples of Magic Functions:
12. unlink() Function
The unlink()
function is used to delete a file.
Example
unlink("myfile.txt");
13. unset() Function
The unset()
function is used to unset a variable.
Example:
$x = 10;
unset($x);
14. Persistent Cookie
A persistent cookie is a cookie that is stored on the user's computer for a specified period of time, or until it is manually deleted. It is used to store information that needs to be remembered across multiple sessions, such as user preferences or login information.
OOPs Question
1. What are Interfaces?
In object-oriented programming, an interface is a blueprint of a class that specifies a set of methods that a class must implement. It defines a contract that classes must adhere to. Interfaces do not contain method implementations; they only declare the methods that a class must provide.
Key characteristics of interfaces:
2. Difference between Abstract Classes and Interfaces
Feature | Abstract Class | Interface |
---|---|---|
Inheritance | Single inheritance | Multiple inheritance |
Method implementation | Can have both abstract and concrete methods | Only abstract methods |
Constructors | Can have constructors | Cannot have constructors |
Variables | Can have variables (both static and non-static) | Cannot have variables |
Access modifiers | Can have any access modifier (public, protected, private) | Only public and static final |
Export to Sheets
3. What are Static Methods?
Static methods are methods that belong to a class rather than an instance of a class. They can be called directly on the class name without creating an object of that class.
Key characteristics of static methods:
4. What is Dependency Injection?
Dependency injection is a design pattern where objects receive their dependencies from external sources rather than creating them themselves. This promotes loose coupling and testability.
Types of Dependency Injection:
5. What is Dynamic Binding?
Dynamic binding, also known as late binding, is the process of determining the method to be called at runtime based on the actual object type, rather than the declared type. This is achieved through polymorphism.
Key characteristics of dynamic binding:
Laravel Question
1. Auth in Laravel
Laravel's authentication system provides a simple way to authenticate users. It handles user registration, login, logout, password reset, and more. Key components include:
Illuminate\Foundation\Auth\User
model. It defines user attributes like name, email, password, etc.2. delete() vs. softDeletes()
deleted_at
timestamp. The record remains in the database but is hidden from queries by default. This is useful for scenarios where you want to keep a record of deleted data for auditing or recovery purposes.3. Eloquent ORM
Eloquent ORM (Object-Relational Mapper) is a powerful tool for interacting with your database. It allows you to work with database tables as objects, simplifying complex database operations. Key features include:
4. Routing
Routing defines how incoming HTTP requests are mapped to specific controller actions or closures. Laravel's routing system is flexible and allows you to define routes using various methods:
5. Middleware in Laravel
Middleware provides a mechanism to filter incoming HTTP requests. It can be used for various purposes, such as:
6. Helpers in Laravel
Helpers are functions that provide common functionality and can be used throughout your application. Laravel comes with a set of built-in helpers, and you can also create your own. Some common helpers include:
By understanding these core concepts, you can effectively build robust and scalable Laravel applications.
JS Question
14. Difference between var, let, and const
Feature | var | let | const |
---|---|---|---|
Scope | Function scope or global scope | Block scope | Block scope |
Redeclaration | Allowed | Not allowed | Not allowed |
Hoisting | Hoisted to the top of its scope | Hoisted but not initialized | Hoisted but not initialized |
Mutable | Mutable | Mutable | Immutable |
Export to Sheets
Example:
function test() {
var x = 10;
let y = 20;
const z = 30;
if (true) {
var x = 40; // Redeclaration allowed
let y = 50; // New variable in block scope
// const z = 60; // Cannot redeclare const
}
console.log(x); // Output: 40
console.log(y); // Output: 20
console.log(z); // Output: 30
}
15. Difference between .each and .each∗∗∗∗∗.each:∗∗ThisisanativeJavaScriptmethodthatiteratesoverarraysandarray−likeobjects(likeNodeLists).Ittakesacallbackfunctionasanargumentthatisexecutedforeachelementinthearray.∗∗∗.each: This is a jQuery method that provides a more flexible way to iterate over arrays, objects, and jQuery object collections. It also takes a callback function, but it offers more features like breaking the loop and accessing the index of the current element.
Example:
// Native JavaScript .each
const numbers = [1, 2, 3];
numbers.forEach(function(number) {
console.log(number);
});
// jQuery $.each
$.each([1, 2, 3], function(index, value) {
console.log(index + ": " + value);
});
16. Chaining AJAX Requests
To chain AJAX requests, you can use the success
callback function of each request to trigger the next one. Here's an example using jQuery's $.ajax
:
$.ajax({
url: "url1",
success: function(data1) {
// Process data1
$.ajax({
url: "url2",
success: function(data2) {
// Process data2
$.ajax({
url: "url3",
success: function(data3) {
// Process data3
}
});
}
});
}
});
17. Arrow Functions
Arrow functions provide a concise syntax for writing anonymous functions. They are especially useful for short functions and can be used to simplify code.
Basic Syntax:
const myFunction = (arg1, arg2) => {
// Function body
};
Concise Syntax:
If the function body consists of a single expression, you can omit the curly braces and the return
keyword:
const square = x => x * x;
Key Points:
this
binding. They inherit the this
value from the enclosing scope.
MySQL Questions and Answers
1. Different Storage Engines in MySQL
MySQL offers various storage engines, each with its own characteristics and use cases:
2. Indexing in MySQL and Its Disadvantage
Indexing is a technique to create a data structure that improves the speed of data retrieval operations in a database table. It works by creating an index, which is a sorted structure that references the rows in the table.
Disadvantage of Indexing:
3. Views in MySQL
A view is a virtual table based on the result-set of an SQL statement. It doesn't store actual data but provides a different way to look at the data.
Why Use Views:
4. Triggers in MySQL
A trigger is a special kind of stored procedure that automatically executes when a specific event occurs on a table.
Types of Events or Actions:
5. Joins in MySQL
Joins are used to combine rows from two or more tables, based on a related column between them.
Types of Joins:
6. Query for 2nd Highest Salary
SELECT Salary
FROM Emp
ORDER BY Salary DESC
LIMIT 1 OFFSET 1;
7. Primary Key vs. Foreign Key
8. Counting Addresses per Employee
SELECT Emp_id, COUNT(*) AS AddressCount
FROM Emp_detail
GROUP BY Emp_id;
9. Getting Records Matching Both Tables
SELECT *
FROM Emp
INNER JOIN Emp_detail ON Emp.Id = Emp_detail.Emp_id;
10. Counting Duplicate Entries
SELECT field_name, COUNT(*) AS DuplicateCount
FROM table_name
GROUP BY field_name
HAVING COUNT(*) > 1;
11. Formatting Gender
SELECT CASE WHEN gender = 1 THEN 'Male' ELSE 'Female' END AS Gender
FROM Users;
12. Deleting Duplicate Entries
DELETE t1
FROM table_name t1
INNER JOIN (
SELECT MIN(id) AS id
FROM table_name
GROUP BY field_name
) t2 ON t1.id = t2.id
WHERE t1.id <> t2.id;
13. Fetching Users Without Orders
SELECT *
FROM Users
WHERE id NOT IN (
SELECT DISTINCT User_id
FROM Orders
);
0 Comments
Leave a Comment