🐘 PHP Beginner

How do you connect to a MySQL database in PHP?

Why Interviewers Ask This

This is a classic screening question for PHP roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

Answer

PHP provides two extensions for MySQL: MySQLi (MySQL Improved) and PDO (PHP Data Objects). MySQLi: $conn = new mysqli("host", "user", "pass", "dbname"); if ($conn->connect_error) { die("Connection failed"); }. It is MySQL-specific. PDO is the modern, recommended approach: $pdo = new PDO("mysql:host=localhost;dbname=mydb", "user", "pass", [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);. PDO supports 12+ database drivers (MySQL, PostgreSQL, SQLite, etc.), making it portable. Both support prepared statements for SQL injection prevention. The old mysql_* functions were removed in PHP 7 — never use them.

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last PHP project, I used this when...' immediately makes your answer more credible and memorable.