<?php /* * 开启pdo,php.ini扩展打开即可 预处理: 1,? 绑定 $stmt->bindparam('1',$name,PDO::PARAM_STR); //从1始 2,:name $stmt->bindparam(':name',$name); 第三个参数可写可不写 3,execute(数组); 如何获得受影响行,插入ID rowCount() lastInsertId() 结果集遍历:4种 1,query来foreach $result = $pdo->query() 可直接foreach $result 2,bindColumn 绑定列 while($stmt->fetch()) 3,fetch while($row=$stmt->fetch(PDO::FETCH_ASSOC)) 4,fetchAll $stmt->fetchall() 返回的是个数组 如何获取字段[了解] */ try{ $dsn = 'mysql:host=localhost;dbname=test'; //手册查询 $pdo = new Pdo($dsn,'root','abc123'); //第四个参数 可初始化设置 $pdo->query('set names utf8'); //字符集 $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); //字段 select id,username,password from user $stmt = $pdo->prepare('desc user'); $stmt->execute(); $j = $stmt->columnCount(); //统计列数 for($i=0;$i<$j;$i++){ echo '<pre>'; var_dump($stmt->getColumnMeta($i)); echo '</pre>'; } $stmt->setFetchMode(PDO::FETCH_NUM); //PDO::FETCH_NUM //PDO::FETCH_ASSOC /* 可直接遍历 $result = $pdo->query('select username,password from user'); foreach($result as $key=>$value){ echo $value['username'].$value['password'].'<br>'; } */ /* execute(数组); fetchAll 遍历 $stmt = $pdo->prepare('select username,password from user where id>:id and username=:username'); $stmt->execute(array(':id'=>120,':username'=>'养生')); //带不带冒号均可 $result = $stmt->fetchAll(); foreach($result as $value){ echo $value['password'].'<br>'; } */ /* //:id fetch遍历 $stmt = $pdo->prepare('select username,password from user where id>:id'); $stmt->bindparam(':id',$id,PDO::PARAM_INT); $id = 122; $result = $stmt->execute(); while($row = $stmt->fetch()){ echo $row['username'].$row['password']; echo '<br>'; } */ /* //绑定列 bindcolumn $stmt = $pdo->prepare('select username,password from user where id>?'); // $stmt->bindparam('1',$p1,PDO::PARAM_STR); // $stmt->bindparam('2',$p2,PDO::PARAM_STR); $stmt->bindparam('1',$p3,PDO::PARAM_INT); // $p1 = 'username'; // $p2 = 'password'; $p3 = 120; $stmt->execute(); $stmt->bindcolumn('username',$username); $stmt->bindcolumn('password',$password); while($stmt->fetch()){ echo $username; echo $password; echo '<br>'; } */ }catch(PDOException $e){ echo $e->getMessage(); } ?>