Tutorial Details

Interview Question of php laravel msql and js
14 Dec

Interview Question of php laravel msql and js

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:

  • $_GET: Used to collect form data sent with the GET method.
  • $_POST: Used to collect form data sent with the POST method.
  • $_REQUEST: Used to collect data sent with both GET and POST methods.
  • $_SESSION: Used to store session variables.
  • $_COOKIE: Used to store cookie variables.
  • $_SERVER: Used to store information about the server environment.
  • $_FILES: Used to store information about uploaded files.

2. Print vs. Echo

Both print and echo are used to output strings in PHP. However, there are some subtle differences:

  • Syntax:
    • print: A language construct, used with parentheses.
    • echo: A language construct, can be used with or without parentheses.
  • Return Value:
    • print: Always returns 1.
    • echo: Doesn't return a value.
  • Multiple Arguments:
    • 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:

  • __construct(): Called when an object is created.
  • __destruct(): Called when an object is destroyed.

Example:

class MyClass {
    public function __construct() {
        echo "Object created";
    }

    public function __destruct() {
        echo "Object destroyed";
    }
}

$obj = new MyClass();

4. Session and Cookie

  • Session: A mechanism to store information on the server side for a specific user session. It's used to maintain user state across multiple page requests.
  • Cookie: A small piece of data sent from a server to a user's web browser, stored on the user's computer. It's used to store information about the user, such as preferences or login status.

5. Ways to Define a Constant

There are two ways to define a constant in PHP:

  • Using the define() function: PHP
    define("PI", 3.14159);
    
  • Using the 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:

  • "r": Read mode
  • "w": Write mode (creates a new file or overwrites an existing one)
  • "a": Append mode (opens a file for writing, appending data to the end)
  • "x": Create mode (creates a new file, fails if the file already exists)

Example:

$file = fopen("myfile.txt", "r");

7. Implode() vs. Explode()

  • implode(): Joins array elements into a string.
  • explode(): Splits a string into an array.

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.

  • $$: Represents a variable variable. It's a variable whose name is stored in another 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:

  • __construct(): Called when an object is created.
  • __destruct(): Called when an object is destroyed.
  • __get(): Called when a non-existent property is accessed.
  • __set(): Called when a non-existent property is assigned a value.
  • __call(): Called when a non-existent method is called.
  • __toString(): Called when an object is cast to a string.

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:

  • Purely abstract: Interfaces only contain method signatures, not implementations.
  • Multiple inheritance: A class can implement multiple interfaces, unlike single inheritance with classes.
  • Polymorphism: Interfaces enable polymorphism, allowing objects of different classes to be treated as if they were of the same type, as long as they implement the same interface.

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:

  • Class-level methods: They are associated with the class itself, not with specific objects.
  • No access to instance variables: They cannot access instance variables directly, as they don't belong to a specific object.
  • Useful for utility functions: They are often used for utility functions that don't require access to object-specific data.

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:

  • Constructor Injection: Dependencies are injected through the constructor.
  • Setter Injection: Dependencies are injected through setter methods.
  • Method Injection: Dependencies are injected as method parameters.

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:

  • Runtime resolution: The method to be called is decided at runtime.
  • Polymorphism: It's essential for polymorphic behavior, where objects of different classes can be treated as if they were of the same type.
  • Virtual methods: In languages like C++, virtual methods enable 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:

  • Authentication Guards: These define how users are authenticated. Laravel comes with a default guard that uses sessions, but you can create custom guards for different authentication methods (e.g., API tokens, OAuth).
  • User Model: This model represents your application's users and typically extends the Illuminate\Foundation\Auth\User model. It defines user attributes like name, email, password, etc.
  • Authentication Middleware: This middleware checks if a user is authenticated and redirects them to the login page if not.

2. delete() vs. softDeletes()

  • delete(): Permanently removes a record from the database. It's irreversible.
  • softDeletes(): Marks a record as deleted by setting a 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:

  • Model Definition: Define models that represent database tables.
  • Query Builder: Create complex database queries using a fluent interface.
  • Relationships: Define relationships between models (e.g., one-to-one, one-to-many, many-to-many).
  • Eloquent Events: Trigger events for specific model actions (e.g., created, updated, deleted).

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:

  • Basic Routing: Simple routes that map a URI to a controller action or closure.
  • Resource Routing: Quickly define routes for CRUD operations on a resource.
  • Route Groups: Group routes together with shared attributes like middleware or prefixes.

5. Middleware in Laravel

Middleware provides a mechanism to filter incoming HTTP requests. It can be used for various purposes, such as:

  • Authentication: Checking if a user is authenticated.
  • Authorization: Verifying user permissions.
  • Logging: Logging requests and responses.
  • Rate Limiting: Limiting the number of requests a user can make.
  • CORS: Handling Cross-Origin Resource Sharing.

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:

  • URL Helpers: Generating URLs.
  • Form Helpers: Creating HTML forms.
  • Array Helpers: Manipulating arrays.
  • String Helpers: Manipulating strings.
  • Date and Time Helpers: Working with dates and times.

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:

  • Arrow functions do not have their own this binding. They inherit the this value from the enclosing scope.
  • They can be used as callback functions, event handlers, and in many other contexts.
  • They often make code more readable and concise.

 

MySQL Questions and Answers

1. Different Storage Engines in MySQL

MySQL offers various storage engines, each with its own characteristics and use cases:

  • InnoDB: The default and most widely used engine, known for its ACID compliance, row-level locking, and support for foreign key constraints.
  • MyISAM: A high-performance engine suitable for read-heavy workloads, offering fast full-text search capabilities.
  • Memory: Stores data in memory for extremely fast access, but data is lost on server restart.
  • Merge: Combines multiple MyISAM tables into a single logical table.
  • Archive: Stores compressed, non-indexed data for long-term storage and analysis.
  • Blackhole: Discards all data written to it, useful for testing and debugging.
  • CSV: Stores data in CSV format, allowing easy import and export.
  • FEDERATED: Accesses data from other MySQL servers.
  • NDB Cluster: A distributed storage engine for high availability and scalability.

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:

  • Increased Storage Space: Indexes consume additional disk space.
  • Slower Data Insertion and Update: Inserting and updating data becomes slower as indexes need to be updated as well.

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:

  • Simplify Complex Queries: Views can encapsulate complex queries, making them easier to understand and use.
  • Security: Views can restrict access to specific data, enhancing security.
  • Data Independence: Changes to underlying tables can be hidden from users who interact with the view.

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:

  • INSERT: Triggered when a new row is inserted into a table.
  • UPDATE: Triggered when an existing row is updated.
  • DELETE: Triggered when a row is deleted from a table.

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:

  • INNER JOIN: Returns rows that have matching values in both tables.  
  • LEFT JOIN: Returns all rows from the left table, and the matched rows from the right table.
  • RIGHT JOIN: Returns all rows from the right table, and the matched rows from the left table.  
  • FULL OUTER JOIN: Returns all rows when there is a match in either left or right table.  
  • CROSS JOIN: Returns the Cartesian product of two tables.

6. Query for 2nd Highest Salary

SELECT Salary
FROM Emp
ORDER BY Salary DESC
LIMIT 1 OFFSET 1;

7. Primary Key vs. Foreign Key

  • Primary Key: Uniquely identifies each row in a table.
  • Foreign Key: References the primary key of another table, establishing a relationship between the two tables.

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