用PDO对数据库进行增,删,改操作,并查询最后的结果

原创 2018-11-30 15:25:27 1361
摘要:<?php//连接数据库try{    $pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu;charset=utf8','root','root');}catch(PDOException $e){    exit ($e->getMessage(

<?php
//连接数据库
try{
   $pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu;charset=utf8','root','root');
}catch(PDOException $e){
   exit ($e->getMessage());
}
//创建SQL语句
$insert = "INSERT INTO `user`(`name`,`email`,`password`,`status`,`create_time`) VALUES (:iname,:iemail,:ipassword,:istatus,:icreate_time)";
$update = "UPDATE `user` SET `name`=:uname,`age`=:uage WHERE `user_id`=:uid";
$delete = "DELETE FROM `user` WHERE `user_id`=:did";
$select = "SELECT `user_id`,`name`,`sex`,`age`,`create_time` FROM `user` WHERE `status`=:status";
//创建预处理对象
$stmt_insert = $pdo->prepare($insert);
$stmt_update = $pdo->prepare($update);
$stmt_delete = $pdo->prepare($delete);
$stmt_select = $pdo->prepare($select);
//参数绑定
$stmt_insert->bindValue(':iname','Angel',PDO::PARAM_STR);
$stmt_insert->bindValue(':iemail','Angel@qq.com',PDO::PARAM_STR);
$stmt_insert->bindValue(':ipassword',sha1('123456'),PDO::PARAM_STR);
$stmt_insert->bindValue(':istatus',1,PDO::PARAM_INT);
$stmt_insert->bindValue(':icreate_time',time(),PDO::PARAM_INT);
$stmt_update->bindValue(':uname','齐天大圣',PDO::PARAM_STR);
$stmt_update->bindValue(':uage',500,PDO::PARAM_INT);
$stmt_update->bindValue(':uid',4,PDO::PARAM_INT);
$stmt_delete->bindValue(':did',1,PDO::PARAM_INT);
$stmt_select->bindValue(':status',1,PDO::PARAM_INT);
//执行
$stmt_insert->execute();
$stmt_update->execute();
$stmt_delete->execute();
$stmt_select->execute();
//遍历结果
$stmt_select->bindColumn(1,$id,PDO::PARAM_INT);
$stmt_select->bindColumn(2,$name,PDO::PARAM_STR);
$stmt_select->bindColumn(3,$sex,PDO::PARAM_STR);
$stmt_select->bindColumn(4,$age,PDO::PARAM_STR);
$stmt_select->bindColumn(5,$create,PDO::PARAM_STR);

while($stmt_select->fetch(PDO::FETCH_BOUND)){
   $rows[] = compact('id','name','sex','age','create');
}


?>
<html>
<style>
   table,th,td{
       border:2px solid #666;
   }
   table{
       text-align:center;
       border-collapse:collapse;
       width:50%;
       margin:30px auto;
   }
   table tr:first-child{
       background-color:lightseagreen;
   }
   caption{
       background-color:lightcoral;
   }
</style>
<table>
   <caption>用户信息表</caption>
   <tr>
       <th>用户ID</th>
       <th>姓名</th>
       <th>性别</th>
       <th>年龄</th>
       <th>创建时间</th>
   </tr>
   <?php foreach($rows as $me) : ?>
       <tr>
           <td><?php echo $me['id'] ?></td>
           <td><?php echo $me['name']?></td>
           <td><?php if($me['sex']==0){echo '男';}else{echo '女';} ?></td>
           <td><?php echo $me['age'] ?></td>
           <td><?php echo date('Y/m/d',$me['create']) ?></td>

       </tr>
   <?php endforeach; ?>
</table>
</html>
zz.jpg

批改老师:天蓬老师批改时间:2018-11-30 16:03:21
老师总结:下次将这些操作,分开写,不要写到一个脚本中,或者创建函数完成

发布手记

热门词条