PHP PDO使用prepare()方法和execute()方法执行SQL语句
在PHP PDO中,预处理语句包括两个方法:prepare()方法和execute()方法。
首先,通过prepare()方法做查询的准备工作,然后,通过execute()方法执行查询。并且还可以通过bindParam()方法来绑定参数提供给execute()方法。
prepare()方法的语法格式如下:
PDOStatement PDO::prepare(string statement[,array driver_options])
execute()方法的语法格式如下:
bool PDOStatement::execute([array input_parameters])
提示
如果只是执行一次查询,query()方法是较好的选择;如果多次执行SQL语句,最好使用prepare()方法和execute()方法。
实例
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>PHP PDO使用prepare()方法和execute()方法执行SQL语句实例-www.baike369.com</title> </head> <body> <table width="300" border="1"> <tr> <th>id</th> <th>学生</th> <th>语文</th> <th>数学</th> <th>英语</th> </tr> <?php $dbms='mysql'; // 数据库类型,使用不同的数据库时,修改此处即可 $dbname='db_xuesheng'; // 使用的数据库 $user='root'; // 数据库连接用户名 $pwd='1234'; // 对应的密码 $host='localhost'; // 数据库主机名 $dsn="$dbms:host=$host;dbname=$dbname"; try{ $pdo=new PDO($dsn,$user,$pwd); // 初始化一个PDO对象,即创建了数据库连接对象$pdo $pdo->query("set names GBK"); // 解决乱码 $query="select * from tb_chengji"; // 定义SQL语句 $result=$pdo->prepare($query); // 准备查询语句 $result->execute(); // 执行查询语句,并返回结果集 // 循环输出查询结果集,设置结果集为关联数组 while($res=$result->fetch(PDO::FETCH_ASSOC)){ ?> <tr> <td><?php echo $res['id'];?></td> <td><?php echo $res['xuesheng'];?></td> <td><?php echo $res['yuwen'];?></td> <td><?php echo $res['shuxue'];?></td> <td><?php echo $res['yingyu'];?></td> </tr> <?php } }catch(Exception $exception){ echo $exception->getMessage(); } ?> </table> </body> </html>
在浏览器中查看PHP PDO使用prepare()方法和execute()方法执行SQL语句的显示效果。如下图所示:
提示
如果将网页的编码设置为utf-8:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
则不会有乱码出现。