What are the advantages of using PDO or mysqli_* functions over the deprecated mysql_query function in PHP?
The mysql_query function is deprecated in PHP and should not be used due to security vulnerabilities and lack of support. It is recommended to use either PDO (PHP Data Objects) or mysqli_* functions for database operations in PHP. These alternatives provide better security features, support for prepared statements, and compatibility with different database systems.
// Using PDO to connect to a MySQL database and perform a query
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM table_name");
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
// Process the data
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}