PHP, short for Hypertext Preprocessor, is a powerful and open-source scripting language that runs on the server. It's mainly used to build dynamic websites and web apps, but it's flexible enough for general programming tasks too.
JavaScript Interview Questions
Prepare for your next interview with these carefully curated questions
1. What is PHP and why is it used?
Answer
Tips
- Mention that PHP is embedded into HTML and powers popular platforms like WordPress
2. What are the differences between echo and print in PHP?
Answer
echo can display one or more strings, quickly and does not return a value. print can only affect one string and returns 1, so it can be used in expressions.
Tips
- Use echo when speed matters, print when a return value is needed
3. How do you connect to a MySQL database using PHP?
Answer
$dbConnect = new mysqli("127.0.0.1", "db_user", "db_password", "user_db");
if ($dbConnect->connect_error){
die("Connection failed: " . $dbConnect->connect_error);
}
Tips
- Always use prepared statements to prevent SQL injection
4. What are sessions and cookies in PHP?
Answer
Session: Stores data on the server.
Cookie: Stores data on the client-side (browser).
Tips
- Use sessions for sensitive data like user login; use cookies for preferences like themes
5. What is the difference between require and include?
Answer
require will produce a fatal error and stop the script if the file is not found.
include will only produce a warning and continue the script.
Tips
- Use require for important files like configuration and database connections
6. How to prevent SQL injection in PHP?
Answer
Using prepared statements in PDO or MySQLi is a smart way to keep your database safe from SQL injection — it’s like putting a security lock on every query you run.
$fetchQuery = "SELECT * FROM users WHERE email = ?";
$stmt = $dbConnect->prepare($fetchQuery);
$stmt->bind_param("s", $email);
$stmt->execute();
Tips
- Never trust user input
- Always sanitize and validate
7. What is the difference between GET and POST methods?
Answer
GET: Data is visible in the URL, used for fetching data.
POST: Data is hidden, used for sending data securely.
Tips
- Use POST for forms involving sensitive data like passwords
8. Explain the difference between == and ===
Answer
= checks value equality.
=== checks value and type equality.
"5" == 5 // true
"5" === 5 // false
Tips
- Always use === for strict type checking
9. What is the use of isset() and empty()?
Answer
isset(): Checks if a variable is set and not null.
empty(): Checks if a variable is empty( 0,"", null, false, etc.).
Tips
- Use both to handle form data safely
10. What are PHP Traits?
Answer
Traits are a mechanism for code reuse in single inheritance. It allows you to create reusable methods across classes.
trait Logger {
public function log($msg) {
echo $msg;
}
}
class MyClass {
use Logger;
}
Tips
- Use traits to avoid duplicating utility methods across classes