PDO的方法
- 連接配接資料庫 new PDO()
- 執行 (exce)
- 查詢 (query)
- 擷取資料 (fetch)
$pdo = new PDO("mysql:host=localhost;dbname=test", 'root', 'root');
// 寫入傳回的是 0,1 失敗,成功
$sql = "insert into tb1(username,age,salary) values('aaa','20',2000.50)";
if ($pdo->exec($sql)) { // 執行,修改,新增用,删除
echo "插入成功!";
} else {
var_dump($pdo->errorInfo());
}
$sql = "select * from tb1";
$rs = $pdo->query($sql); //查詢
$rows = [];
while ($row = $rs->fetch(PDO::FETCH_ASSOC)) {
array_push($rows, $row);
}
echo "<table >";
foreach ($rows as $v) {
echo "<tr>";
echo "<td>".$v["username"]."</td>";
echo "<td>".$v["age"]."</td>";
echo "<td>".$v["salary"]."</td>";
echo "</tr>";
}
echo "</table>";
exit;
// 删除和修改執行後會傳回u受影響的行數
// 删除
$sql = "delete from tb1 where username='aaa'";
$ret = $pdo->exec($sql);
// 修改
$sql = "update tb1 set username = 'acun' where username='tom'";
$ret = $pdo->exec($sql);
var_dump($ret);