1. connect.php(数据库连接文件,创建PDO对象):
<?php header("content-type:text/html;charset=utf-8"); try{ $pdo=new PDO("mysql:host=localhost;dbname=demo;charset=utf8",'root','root'); }catch (PDOException $e){ echo $e->getMessage(); die(); }
2. pdo_insert.php(实现数据添加功能):
<?php require 'public/connect.php'; $data=['name'=>'小龙女','email'=>'xln@php.cn','password'=>sha1('123')]; $sql="INSERT INTO `student` SET `name`='{$data['name']}',`email`='{$data['email']}',`password`='{$data['password']}'"; $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING); try{ $num=$pdo->exec($sql); if($num){ echo $num."条数据被插入数据库!"; } }catch (PDOException $e){ echo $e->getMessage(); } unset($pdo);
3. pdo_select.php(实现数据查询(列表)功能):
<?php require 'public/connect.php'; $sql="SELECT `id`,`name`,`email` FROM `student`"; $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING); try{ $pdoStmt=$pdo->query($sql); if($pdoStmt){ foreach ($pdoStmt as $row){ echo 'ID:'.$row['id'].' name:'.$row['name'].' email:'.$row['email'].'<br/>'; } echo '总共有'.$pdoStmt->rowCount().'条数据!'; unset($pdoStmt); } }catch (PDOException $e){ echo $e->getMessage(); } unset($pdo);
4. pdo_update.php(实现数据更新功能):
<?php require 'public/connect.php'; $data=['name'=>'乔峰','email'=>'qf@php.cn']; $sql="UPDATE `student` SET `name`='{$data['name']}',`email`='{$data['email']}' WHERE `id`=1"; $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING); try{ $num=$pdo->exec($sql); if($num){ echo $num."条数据被更新!"; }else{ echo '无数据被更新!'; } }catch (PDOException $e){ echo $e->getMessage(); } unset($pdo);
5. pdo_delete.php(实现数据删除功能):
<?php require 'public/connect.php'; $sql="DELETE FROM `student` WHERE `id`=1"; $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING); try{ $num=$pdo->exec($sql); if($num){ echo '成功删除'.$num.'条数据!'; } }catch (PDOException $e){ echo $e->getMessage(); } unset($pdo);