PDO是数据访问抽象层,是一种类,可以操作任何一个数据库,用于多个数据库的使用和转换,非常方便
查询:
<?php //造DSN:驱动名:dbname=数据库名;host=服务器地址 $dsn = "mysql:dbname=mydb;host=localhost" //造PDO对象 $pdo = new PDO($dsn,"root",""); //写SQL语句 $sql = select * from Info //预处理 准备一条SQL语句 $stm = $pdo->prepare($sql); //执行SQL语句 if($stm->execute()) { //1.逐行取数据 var_dump($stm->fetch()); //2.取所有数据 var_dump($stm->fetchAll()); //3.取某一列 var_dump(fetchColumn(1)); //4.返回对象 var_dump($stm->fetchObject()); } else { echo "执行失败"; } ?>
添加:
<?php $dsn = "mysql:dbname=mydb;host=localhost"; $pdo = new PDO($dsn,"root",""); $sql = "insert into Nation values(?,?)";//方法一 //$sql = "insert into Ntion values(:code,:name)";//方法二 $stm = $pdo->prepare($sql); //给参数绑定值 $attr = array("p010","维吾尔族");//方法一 //$attr = array("code"=>"p010","name"=>"维吾尔族");//方法二 if($stm->execute($attr)) { echo "添加成功"; } else { echo "添加失败"; } ?>
时间: 2024-10-25 07:12:37