PHP PDO使用prepare()方法和execute()方法执行SQL语句

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语句的显示效果。如下图所示:

在浏览器中查看PHP PDO使用prepare()方法和execute()方法执行SQL语句的显示效果


提示

如果将网页的编码设置为utf-8:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

则不会有乱码出现。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值