What are the differences between using mysqli and PDO for database access in PHP?
When it comes to database access in PHP, mysqli and PDO are two popular options. mysqli is specific to MySQL databases and offers both procedural and object-oriented methods for interacting with the database. It is considered to be easier for beginners to learn due to its similarity to the older MySQL extension. On the other hand, PDO is a database abstraction layer that supports multiple database systems, making it more versatile. It also provides a more secure way to interact with databases by using prepared statements to prevent SQL injection attacks. Overall, the choice between mysqli and PDO depends on the specific project requirements and personal preference.
// Example using mysqli
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if ($mysqli->connect_error) {
die('Connection failed: ' . $mysqli->connect_error);
}
$result = $mysqli->query("SELECT * FROM table");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row['id'] . " Name: " . $row['name'];
}
}
$mysqli->close();
```
```php
// Example using PDO
$dsn = 'mysql:host=localhost;dbname=database';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
$stmt = $pdo->query("SELECT * FROM table");
while ($row = $stmt->fetch()) {
echo "ID: " . $row['id'] . " Name: " . $row['name'];
}
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}