🐘 PHP
Beginner
How do you connect to a MySQL database in PHP?
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.
Previous
What are PHP date and time functions?
Next
What are prepared statements and why are they important?