如果你对该文章中的内容有疑问/不解,可以点击此处链接提问
要注明问题和此文章链接地址 点击此处跳转
PDO实现数据库的增删改查
//链接数据库 $pdo = new PDO('mysql:host=localhost;dbname=test','root','root'); //增 $res = $pdo->exec("insert into user(name) values('测试1')"); if($res){ echo '添加成功数据ID为:'.$pdo->lastinsertid().'<br/>'; } $res = $pdo->query("insert into user(name) values('测试2')"); if($res){ echo '添加成功数据ID为:'.$pdo->lastinsertid().'<br/>'; } //删 $res = $pdo->exec("delete from user where id=4"); if($res){ echo "删除成功"; } $res = $pdo->query("delete from user where id=5"); if($res){ echo "删除成功"; } //改 $res = $pdo->exec("update user set name='xx' where id=2 "); if($res){ echo "更新成功"; } $res = $pdo->query("update user set name='ww' where id=1"); if($res){ echo "更新成功"; echo "影响行数".$res->rowCount(); } //查 $sql = "select * from user"; $res = $pdo->query($sql); $list = $res->fetch(PDO::FETCH_BOTH);//返回单条 $lists = $res->fetchAll(PDO::FETCH_ASSOC);//返回多条 //FETCH_ASSOC 关联数组 //FETCH_NUM 索引数组 //FETCH_BOTH 混合数组 //统计 $num = $pdo->query("select count(*) from user"); echo '共有数据:【'.$num->fetchColumn().'】条'; //设置字符集 $pdo->query('set names utf8');