先實例化PDO對象,並建立測試數據表:php
<?php $dsn = 'mysql:host=localhost;dbname=test;charset=utf8;port=3306'; $user = 'root'; $pass = 'root'; $pdo = new PDO($dsn, $user, $pass);
測試數據表:html
create table tn_pdo( id int primary key auto_increment, username varchar(32), password varchar(64) )engine myisam default charset utf8;
PDO::exec() 返回受修改或刪除 SQL 語句影響的行數。若是沒有受影響的行,則 PDO::exec() 返回 0。mysql
<?php $dsn = 'mysql:host=localhost;dbname=test;charset=utf8;port=3306'; $user = 'root'; $pass = 'root'; $pdo = new PDO($dsn, $user, $pass); $sql = "insert into tn_pdo values(null, '張三丰', 'admin123')"; $sql = "update tn_pdo set username='李四光' where id=1"; $sql = "delete from tn_pdo where id=1"; $result = $pdo->exec($sql); // 執行一條 SQL 語句,並返回受影響的行數 var_dump($result);
若是成功,PDO::query()返回PDOStatement對象,若是失敗返回 FALSE 。sql