用PDO 读取 员工表里 name age sex字段代码
时间: 2024-05-07 22:24:01 浏览: 114
很高兴为您解答这个问题!以下是用PDO读取员工表里name,age,sex字段的代码,仅供参考:
```
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "连接成功";
$stmt = $conn->prepare("SELECT name, age, sex FROM 员工表");
$stmt->execute();
// 设置结果集为关联数组
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $k=>$v) {
print_r($v);
}
}
catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
$conn = null;
?>
```
希望这个代码对您有所帮助!如果您有任何其他问题,可以随时问我哦!
阅读全文