What are the advantages of using PDO or mysqli_ over the mysql_ extension in PHP for database operations?
The mysql_ extension in PHP is deprecated and has been removed in PHP 7. It is recommended to use either PDO (PHP Data Objects) or mysqli_ (MySQL Improved) for database operations in PHP as they offer more features, better performance, and are more secure.
// Using PDO for database operations
try {
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM mytable');
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $row) {
// Process each row
}
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
// Using mysqli_ for database operations
$mysqli = new mysqli('localhost', 'username', 'password', 'mydatabase');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$query = "SELECT * FROM mytable";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
// Process each row
}
$result->free();
}
$mysqli->close();