What are some alternatives to MySQLi for database operations in PHP?
MySQLi is a popular extension for PHP to interact with MySQL databases, but there are alternative libraries that can be used for database operations. One such alternative is PDO (PHP Data Objects), which provides a more flexible and consistent way to access databases, as it supports multiple database types, not just MySQL.
// Using PDO for database operations in PHP
// Connect to the database
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
// Perform a query
$stmt = $pdo->query('SELECT * FROM mytable');
while ($row = $stmt->fetch()) {
// Do something with the data
}
// Close the connection
$pdo = null;