PDO->exec() 方法主要是针对没有结果集合返回的操作,比如 INSERT、UPDATE、DELETE 等操作,它返回的结果是当前操作影响的列数。
语法:
PDO->exec( string statement )
PDO Insert
例子:
<?php //构造PDO连接 $dbh = "mysql:host=localhost;dbname=test"; $db = new PDO($dbh, 'root', 'root123'); $db->query("set character set 'gbk'"); //写入数据 $password = md5("123456"); $regdate = time(); $sql = "INSERT INTO user (username,password,email,regdate)VALUES('小陈','$password','chen@163.com', $regdate)"; $count = $db->exec($sql); echo '写入 ',$count,' 条数据记录!'; $db = null; ?>
执行该例子,浏览器输出:
写入 1 条数据记录!
PDO Update
例子:
<?php //构造PDO连接 $dbh = "mysql:host=localhost;dbname=test"; $db = new PDO($dbh, 'root', 'root123'); $db->query("set character set 'gbk'"); //更新数据 $sql = "UPDATE user SET email='xiaochen@163.com' WHERE username='小陈'"; $count = $db->exec($sql); echo '更新 ',$count,' 条数据记录!'; $db = null; ?>
PDO Delete
例子:
<?php //构造PDO连接 $dbh = "mysql:host=localhost;dbname=test"; $db = new PDO($dbh, 'root', 'root123'); $db->query("set character set 'gbk'"); //删除数据 $sql = "DELETE FROM user WHERE username = '小陈'"; $count = $db->exec($sql); echo '删除 ',$count,' 条数据记录!'; $db = null; ?>