摘要:学会了如何使用PDO类来连接数据库,以及如何查询并遍历在网页上<?php //bindparam(占位符,变量,类型常量) //bindvalue(占位符,值,类型常量) 参数绑定 //bindColumn(列名,变量,类型常量,长度) 列绑定 //pdo连接数据库 $type = 'mysql'; $host =&
学会了如何使用PDO类来连接数据库,以及如何查询并遍历在网页上
<?php
//bindparam(占位符,变量,类型常量)
//bindvalue(占位符,值,类型常量) 参数绑定
//bindColumn(列名,变量,类型常量,长度) 列绑定
//pdo连接数据库
$type = 'mysql'; $host = '127.0.0.1'; $dbname = 'sys'; $charset = 'utf8';
$dsn = "$type:host=$host;dbname=$dbname;charset=$charset"; //数据源
$user = 'root'; $pass = 'root';
//pdo
$pdo = new PDO($dsn,$user,$pass);
try{
$pdo = new PDO($dsn,$user,$pass);
echo '连接成功'.'<hr>';
}catch(PDOException $e){
echo $e->errorInfo;
}
//sql 语句
$sql = "SELECT * FROM `user_table` WHERE `id` > :id ";
//预处理对象
$stmt = $pdo->prepare($sql);
//绑定参数
$idd = 1;
$stmt->bindValue(':id',$idd);
$stmt->execute();
//列绑定
$stmt->bindColumn('id',$id,PDO::PARAM_INT);
$stmt->bindColumn('username',$username,PDO::PARAM_STR,50);
$stmt->bindColumn('password',$password,PDO::PARAM_STR,50);
$stmt->bindColumn('email',$email,PDO::PARAM_STR,50);
//解析遍历结果集
while($stmt->fetch()){
//变量转为数组
$arr [] = compact('id','username','password','email');
}
?>
<html>
<style type="text/css">
.tftable {font-size:12px;color:#333333;width:800px;border-width: 1px;border-color: #729ea5;border-collapse: collapse;}
.tftable th {font-size:12px;background-color:#acc8cc;border-width: 1px;padding: 8px;border-style: solid;border-color: #729ea5;text-align:auto;}
.tftable tr {background-color:#d4e3e5;}
.tftable td {font-size:15px;border-width: 1px;padding: 8px;border-style: solid;border-color: #729ea5;text-align: center;}
.tftable tr:hover {background-color:#ffffff;}
</style>
<table class="tftable" border="1" align="center">
<tr><th>id</th><th>username</th><th>password</th><th>email</th></tr>
<?php foreach($arr as $a){ ?>
<tr>
<td><?php echo $a['id'] ?></td>
<td><?php echo $a['username'] ?></td>
<td><?php echo $a['password'] ?></td>
<td><?php echo $a['email'] ?></td>
</tr>
<?php } ?>
</table>
</html>
批改老师:天蓬老师批改时间:2018-12-23 16:58:20
老师总结:恭喜你掌握了pdo的mysql数据库连接和查询。继续努力加油