在使用PDO查詢數(shù)據(jù)時,可以按照以下步驟進行操作:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database_name";
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();
}
$sql = "SELECT * FROM table_name";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $row) {
echo $row['column_name'];
}
完整的示例代碼如下:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database_name";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
$sql = "SELECT * FROM table_name";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $row) {
echo $row['column_name'];
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
注意替換$servername
、$username
、$password
和$dbname
為實際的數(shù)據(jù)庫連接信息。同時,將table_name
和column_name
替換為實際的表名和列名。