PDO操作数据库的几种方法
用惯了框架,php的pdo都忘得差不多了吧,翻出来初学的笔记,看了看.
①采用pdo::query()方法执行sql语句,返回一个结果集
<?php header('Content-Type:text/html;charset=utf-8'); $dbms='mysql'; $dbname='chaoshi'; $user='root'; $pwd='root'; $host='localhost'; $dsn="$dbms:host=$host;dbname=$dbname"; try{ $pdo=new PDO($dsn,$user,$pwd); echo 'PDO链接数据库成功<br><pre>'; } catch(Exception $e){ echo $e->getMessage()."<br/>"; } $sql="select * from shucai"; $result=$pdo->query($sql); //返回的是查询后的结果集 foreach($result as $value){ //Foreach语句遍历结果集输出每一行的内容 echo $value['name']."<br>"; } |
②采用PDO::exec()方法执行sql语句,返回被影响的行数
<?php header('Content-Type:text/html;charset=utf-8'); //调用pdo::exec()方法返回执行后受影响的条数 try{ $pdo=new PDO("mysql:host=localhost;dbname=chaoshi",'root',"root"); echo "数据库连接成功"; } catch(Exception $e){echo $e->getMessage()."<br>"; } $insertrow=$pdo->exec("insert into shucai values(5,'小熊',2.9)"); $count=$dbh->exec("DELETE FROM shucai WHERE bianhao=11"); echo "插入".$insertrow."删除".$count."行"; |
③采用预处理语句prepare()和execute()方法执行
<?php //预处理语句调用PDO::prepare方法和PDO::execute()方法 $pdo=new PDO("mysql:host=localhost;dbname=chaoshi","root","root"); $sth=$pdo->prepare('SELECT * FROM shucai WHERE bianhao>? AND price>?'); $sth->execute(array(7,1.1)); $res=$sth->fetchAll(PDO::FETCH_ASSOC); //关联数组方式获取数据 echo "<pre>"; var_dump($res); foreach($res as $rows){ echo $rows['bianhao']; echo $rows['name']; echo $rows['price']; echo "<br>"; } |
PDO获取结果集的几种方法
①fetch()方法 获取结果集中的下一行记录
<?php //调用PDO::fetch()方法返回结果集中下一行数据 $pdo=new PDO("mysql:host=localhost;dbname=chaoshi","root","root"); $sth=$pdo->prepare('SELECT * FROM shucai WHERE bianhao>? AND price>?'); $sth->execute(array(7,1.1)); while($row=$sth->fetch(PDO::FETCH_ASSOC)){ echo $row['bianhao']; echo $row['name']; echo $row['price']."<br>"; } |
②FetchColumn()方法 获取结果集中下一行中指定列的值
<?php $pdo=new PDO("mysql:host=localhost;dbname=chaoshi","root","root"); $sql="select name from shucai"; $result=$pdo->prepare($sql); $result->execute(); while($row=$result->fetchColumn()){ echo $row; echo "<br>"; } |
③FetchAll()方法 获取结果集中所有的行
<?php //调用PDO::fetch()方法返回结果集中下一行数据 $pdo=new PDO("mysql:host=localhost;dbname=chaoshi","root","root"); $sth=$pdo->prepare('SELECT * FROM shucai WHERE bianhao>? AND price>?'); $sth->execute(array(7,1.1)); $data=$sth->fetchAll(PDO::FETCH_ASSOC); foreach ($data as $row2){ echo $row2['bianhao']; echo $row2['name']; echo $row2['price']."<br>"; } |