PDO in PHP
PDO (PHP Data Objects) is a database abstraction layer that allows you to work with databases using a consistent interface. PDO supports multiple database drivers and provides built-in security features to prevent SQL injection attacks.
Example:
php
// connect to a database using PDO
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// run a query using PDO
$stmt = $conn->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row) {
echo $row['username'] . " " . $row['email'];
}
No comments:
Post a Comment