PHP-PDO方式访问数据库

PDO方式访问数据库

一、了解PDO访问异构数据库的方法–PDO类实例化、PDO类query( )方法和exec( )方法。注意激活PDO :php_pdo_mysql.dll

<?php
   try {
   	
      $db=new PDO("mysql:host=localhost;dbname=pxscj;", "root", "");
      //实例化PDO类(创建PDO对象)
      //$db=new PDO("sqlsrv:Server=localhost;Database=pxscj;","root",""); //只需要改DSN(数据库源名)
   }
   catch (PDOException $e) {
                                         
   //捕获异常--PDOException(Exception的简单重写)
      echo "数据库连接失败:".$e->getMessage();                   
      //getMessage()--PDOException类中定义的方法
   }
   
   $db->exec("set names utf8mb4");                                 
   //exec()--PDO类的方法(执行没有结果集的SQL语句)
   
   $query="insert into kcb values('606','PHP程序设计',6,48,3)";   //SQL语句
   if($affCount = $db->exec($query)) {
                               
   //执行SQL语句$query--返回值为受影响记录数
     echo "插入成功,受影响条数为:".$affCount."<br><br>";                
   }

   $query="select * from kcb";                                    
   //SQL语句
   foreach($db->query($query) as $row) {
                            
    //执行SQL语句$query--执行有结果集的SQL语句
      echo "课程号:".$row[0]."<br>";                             
       //返回的是一个PDOStatement类(型)的对象
      echo "课程名:".$row[1]."<br>";                              
      //还可以用PDOStatement类的方法fetch()行读
      echo "开课日期:".$row[2]."<br>"; 
      echo "学时:".$row[3]."<br><br>";
   }

?>

二、PDO事务处理

  1. 让MySQL支持InnoDB引擎:注释掉my.ini中的skip-innodb(重启MySQL) (MySQL5.6以上的不需要这一步)
  2. 更改表的引擎:(1) mysql -uroot -h127.0.0.1 -p111 (2) use pxscj; (3) alter table kcb engine = InnoDB;
<?php
   try {
   	
      $db=new PDO("mysql:host=localhost;dbname=pxscj","root","");     
      //实例化PDO类(创建PDO对象)
   }
   catch (PDOException $e) {
                                       
   //捕获异常--PDOException(Exception的简单重写)
      echo "数据库连接失败:".$e->getMessage();                 
      //getMessage()--PDOException类中定义的方法
   }
   try {
      
      $db->exec("set names utf8mb4");                            
      //exec()--PDO类的方法(执行没有结果集的SQL语句)
   
      $db->beginTransaction();                                 //***事务开始***
      
      $affrows=$db->exec("insert into kcb values('506','UML系统分析',5,48,3)");    
      if(!$affrows)
         throw new PDOException("插入失败1");
      $affrows=$db->exec("insert into kcb values('606','PHP程序设计',6,32,2)");  
      if(!$affrows)
         throw new PDOException("插入失败2");
      echo "插入成功!"; 
      $db->commit();                                  //***事务结束***--如果全部成功则提交
   }
   catch (PDOException $e) {
            //捕获异常--PDOException(Exception的简单重写)
      echo $e->getMessage(); 
      $db->rollback();              //回滚(要么成功要么失败)
   }
?>


现在表中有这些内容,现在把'506','UML系统分析',5,48,3这条记录删掉。

delete from kcb where 课程号=506;

select * from kcb;


重新执行PHP代码:

再查看插入结果:

果然,记录'506','UML系统分析',5,48,3虽然插入成功了, 但是由于第二条记录'606','PHP程序设计',6,32,2插入失败,导致整个事务并没有全部成功,只要有失败的,事务就不会提交,并且执行了事务回滚,使记录'506','UML系统分析',5,48,3也没有插入成功。

三、PDOStatement类的方法fetch( )的应用

<?php
  try {
   	
     $db=new PDO("mysql:host=localhost;dbname=pxscj","root","");            
     //实例化PDO类(创建PDO对象)
     //$db=new PDO("sqlsrv:Server=localhost;Database=pxscj;","root","111"); //只需要改DSN(数据库源名)
  }
  catch (PDOException $e) {
                                         
  //捕获异常--PDOException(Exception的简单重写)
     echo "数据库连接失败:".$e->getMessage();                   
     //getMessage()--PDOException类中定义的方法
  }
  $db->exec("set names utf8mb4");                                 
  //exec()--PDO类的方法(执行没有结果集的SQL语句)
  $sql="select * from XSB where 性别=0";                         //SQL语句
  $result=$db->query($sql);                                      
  //执行SQL语句$sql-返回一个PDOStatement类(型)对象
  echo "<table border=1 align='center'>";                        
  //是一个结果集
  echo "<tr><td>学号</td><td>姓名</td><td>总学分</td></tr>";
  while($row=$result->fetch(PDO::FETCH_NUM))         
  //fetch()是PDOStatement类的方法(从结果集行读)
  {
                                                                 
  //返回的是一个键名为数字(PDO::FETCH_NUM)数组
   list($XH, $XM, $XB, $CSSJ, $ZY, $ZXF, $BZ)=$row;                
  //list()将数组中的单元值赋值给变量
   echo "<tr><td>$XH</td><td>$XM</td><td>$ZXF</td></tr>";
  }
  echo "</table>";
?>

四、预定义语句的应用

<?php
   try {
   	
      $db=new PDO("mysql:host=localhost;dbname=pxscj","root","");     
      //实例化PDO类(创建PDO对象)
   }
   catch (PDOException $e) {
                                       
   //捕获异常--PDOException(Exception的简单重写)
      echo "数据库连接失败:".$e->getMessage();                 
      //getMessage()--PDOException类中定义的方法
   }
   $in_sql="insert into userinfo(username,password,sex,age,email) values(?,?,?,?,?)";  //SQL语句$in_sql
   $in_result=$db->prepare($in_sql);                                                  
   //预处理SQL语句$in_sql
   
   $userid="php3"; $pwd1="111111"; $sex=0; $age=36; 
   $email="php3@qq.com";
   
   $in_result->bindParam(1, $userid);        
   //PDOStatement的bindParam()的作用是绑定参数给execute( )
   $in_result->bindParam(2, $pwd1);          
   //SQL语句使用问号参数时--bindParam()第一个参数是问号索引偏移(第几个)
   $in_result->bindParam(3, $sex);           
   //bindParam()第二个参数是赋值给SQL语句参数(问号)的变量
   $in_result->bindParam(4, $age);          
    //可以使用变量参数进行定制
   $in_result->bindParam(5, $email);
   $in_result->execute();                              
   //执行经过预处理的SQL语句$in_result
   
   if($in_result->rowCount()==0)                       
   //用PDOStatement的rowCount()返回结果集行的总数
     echo "<script>alert('插入记录失败!');</script>";
   else
     echo "<script>alert('插入记录成功!');</script>";
?>


五、制作一个登录系统,实现用户注册、用户登录、用户注销、修改密码等功能

  • SY9_5_login.php:
<html>

<head>
  <title>用户登录页面</title>
</head>

<body>
  <form action="" method="post">
    <div align="center">
      <font size="5" color="blue">用户登录</font>
    </div>
    <table align="center">
      <tr>
        <td>用户名:</td>
        <td><input type="text" name="userid"></td>
      </tr>
      <tr>
        <td>密码: </td>
        <td><input type="password" name="pwd" size="21"></td>
      </tr>
      <tr>
        <td colspan="2" align="center"><input type="submit" name="Submit" value="登录">
          <input type="reset" name="Submit2" value="注册" onclick="window.location='SY9_5_regist.php'"></td>
      </tr>
    </table>
  </form>
</body>

</html>
<?php                                                           
  //修改 output_buffering = On 重启Apache
  include "SY9_5_fun.php";                            
  //SY9_5_fun.php(用于连接数据库)
  if(isset($_POST['Submit']))
  {
   
    $userid=$_POST['userid'];         //用户名
    $pwd=$_POST['pwd'];           //密码
    $sql="select * from userinfo where username='$userid'";     //SQL语句
    $result=$db->query($sql);         //执行$sql--执行有结果集的SQL语句
    
    if(list($username,$password,$sex,$age,$email)=$result->fetch(PDO::FETCH_NUM))  
    //用fetch()方法从结果集行读 
    {
     
      if($password==$pwd)                      //判断密码是否正确
      {
   
        session_start();                                                     //开启SESSION
        $_SESSION['userid']=$username;                                       //注册SESSION
        header("location:SY9_5_main.php");                              
        //跳转到主页
      }
      else
        echo "<script>alert('密码错误!');</script>";
    }
    else
      echo "<script>alert('用户名不存在!');</script>";
  }
?>



  • SY9_5_regist.php:
<html>

<head>
  <title>用户注册页面</title>
</head>

<body>
  <form action="" method="post">
    <div align="center">
      <font size="5" color="blue">新用户注册</font>
    </div>
    <table width="340" align="center" border="0">
      <tr>
        <td width="80" align="right">用户名:</td>
        <td><input type="text" name="userid"></td>
        <td>
          <font color="red">*1-20个字符</font>
        </td>
      </tr>
      <tr>
        <td align="right">密码:</td>
        <td><input type="password" name="pwd1" size="21"></td>
        <td>
          <font color="red">*6-20个字符</font>
        </td>
      </tr>
      <tr>
        <td align="right">确认密码:</td>
        <td><input type="password" name="pwd2" size="21"></td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td align="right">性别:</td>
        <td><input type="radio" name="sex" value="1"><input type="radio" name="sex" value="0"></td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td align="right">年龄:</td>
        <td><input type="text" name="age"></td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td align="right">email:</td>
        <td><input type="text" name="email"></td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td colspan="3" align="center"><input type="submit" name="Submit" value="提交">
          <input type="reset" name="Submit2" value="重置"></td>
      </tr>
    </table>
  </form>
</body>

</html>
<?php
  if(isset($_POST['Submit']))
  {
   
    $userid=$_POST['userid'];
    $pwd1=$_POST['pwd1'];
    $pwd2=$_POST['pwd2'];
    $sex=$_POST['sex'];
    $age=$_POST['age'];
    $email=$_POST['email'];
    $checkid=preg_match('/^\w{1,20}$/',$userid);         
    //使用正则表达式检查用户名
    $checkpwd1=preg_match('/^\w{6,20}$/',$pwd1);
    $checkemail=preg_match('/^[a-zA-Z0-9_\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/',$email);
    if(!$checkid)
       echo "<script>alert('用户名设置错误!');</script>";
    elseif(!$checkpwd1)
       echo "<script>alert('密码设置错误!');</script>";
    elseif(!$sex)
       echo "<script>alert('性别为必选项!');</script>";
    elseif($age&&(!is_numeric($age)))
       echo "<script>alert('年龄必须为一个数字!');</script>";
    elseif($email&&(!$checkemail))
       echo "<script>alert('email格式错误!');</script>";
    elseif($pwd1!=$pwd2)
       echo "<script>alert('两次输入的密码不一致!');</script>";
    else
    {
   
       include "SY9_5_fun.php";                                             
       //连接数据库
       $s_sql="select * from userinfo where username='$userid'";            
       //SQL语句
       $s_result=$db->query($s_sql);                                        
       //query()--PDO类的方法(执行有结果集的SQL语句)
       if($s_result->rowCount()!=0)                                         
       //判断用户名是否已存在
          echo "<script>alert('用户名已存在!');</script>";
       else {
   
        $in_sql="insert into userinfo(username,password,sex,age,email) values(?,?,?,?,?)";  //SQL语句$in_sql
        $in_result=$db->prepare($in_sql);                            
        //预处理SQL语句$in_sql
        $in_result->bindParam(1, $userid);        
        //PDOStatement的bindParam()的作用是绑定参数给execute( )
        $in_result->bindParam(2, $pwd1);          
        //SQL语句使用问号参数时--bindParam()第一个参数是问号索引偏移(第几个)
        $in_result->bindParam(3, $sex);           
        //bindParam()第二个参数是赋值给SQL语句参数(问号)的变量
        $in_result->bindParam(4, $age);
        $in_result->bindParam(5, $email);
        $in_result->execute();                    
        //执行经过预处理的SQL语句$in_result
        if($in_result->rowCount()==0)
           echo "<script>alert('注册失败!');</script>";
        else {
   
           //注册成功后跳转到登录页面
           echo "<script>alert('注册成功!');location.href='SY9_5_login.php';</script>";
        }
       }
    }
  }
?>


  • SY9_5_main.php:
<?php
  session_start();                              //开启SESSION
  $userid=@$_SESSION['userid'];			//取得SESSION值
  if($userid) {
                                    //判断$userid是否为空
     echo "欢迎用户".$userid."登录!<br/>";
     echo "<a href='SY9_5_select.php'>查看个人信息</a>&nbsp;";
     echo "<a href='SY9_5_update.php'>修改密码</a>&nbsp;";
     echo "<a href='SY9_5_delete.php'>注销账户</a>&nbsp;";
     echo "<a href='SY9_5_login.php'>退出</a><br/><br/>";
  }
  else
     echo "对不起,您没有权限访问本页面";
?>

  • SY9_5_select.php:
<?php
   include "SY9_5_main.php";		      //包含主页面
   $username=$_SESSION["userid"];            //取得SESSION值
   if($username)
   {
   
      include "SY9_5_fun.php";                      //连接数据库
      $select_sql="select * from userinfo where username='$username'";    
      //SQL语句
      $select_result=$db->query($select_sql);
      //执行SQL语句
      while(list($username,$password,$sex,$age,$email)=$select_result->fetch(PDO::FETCH_NUM))   
      //行读结果集
      {
   
      	echo "用户名:".$username."<br>";
      	echo "性别:";
      	if($sex==1)
      	   echo "男<br>";
      	else
      	   echo "女<br>";
      	echo "年龄:".$age."<br>";
      	echo "email:".$email;               //输出email
      }
   }
?>

  • SY9_5_update.php:
<?php
  session_start();
  $username=@$_SESSION['userid'];        //取得SESSION值
  if($username){
   
?>
<form action="" method="post">
  <div align="center">
    <font size="5" color="blue">密码修改</font>
  </div>
  <table align="center">
    <tr>
      <td>原密码:</td>
      <td><input type="password" name="oldpwd"></td>
    </tr>
    <tr>
      <td>新密码:</td>
      <td><input type="password" name="newpwd"></td>
    </tr>
    <tr>
      <td colspan="2" align="center"><input type="submit" name="Submit" value="修改">
        <input type="reset" name="Submit" value="重置"></td>
    </tr>
  </table>
</form>
<?php
  }
  else echo "您没有权限访问本页面";
  
  if(isset($_POST['Submit'])) {
   
     include "SY9_5_fun.php";                                                      //连接数据库
     $oldpwd=$_POST['oldpwd'];                                   //原密码
     $newpwd=$_POST['newpwd'];                                   //新密码
     $s_sql="select * from userinfo where username='$username'";
     //SQL语句
     $s_result=$db->query($s_sql);
     //执行SQL语句
     list($username,$password,$sex,$age,$email)=$s_result->fetch(PDO::FETCH_NUM);
     if($oldpwd != $password)                             //判断原密码是否正确
        echo "<script>alert('原密码错误!');</script>";
     else {
   
        $checkpwd=preg_match('/^\w{6,20}$/',$newpwd);
        if(!$checkpwd)
          echo "<script>alert('新密码格式不满足要求!');</script>";
        else {
   
           $update_sql="update userinfo set password='$newpwd' where username='$username'";   //SQL语句
           $affected=$db->exec($update_sql);                                                  
           //执行sql语句$update_sql
           if($affected)   //如果受影响记录数不为0
             echo"<script>alert('密码修改成功!');location.href='SY9_5_main.php';</script>";
           else
             echo "<script>alert('密码修改失败!');</script>";
        }
     }
  }
?>


  • SY9_5_delete.php:
<?php
  include "SY9_5_fun.php";           //连接数据库
  session_start();
  $username=@$_SESSION['userid'];
  $delete_sql="delete from userinfo where username = '$username'";    
  //注销自己的SQL语句
  $affected=$db->exec($delete_sql);                                 
  //执行没有返回的sql语句$delete_sql
  if($affected)                                        //如果受影响记录数不为0
    echo "<script>alert('注销用户成功!');location.href='SY9_5_login.php';</script>";
  else
    echo "<script>alert('注销用户失败!');location.href='SY9_5_main.php';</script>";
?>

  • SY9_5_fun.php:
<?php
  try  {
   	
     $db=new PDO("mysql:host=localhost;dbname=PXSCJ","root","");           
     //实例化PDO类(创建PDO对象)
  }
  catch (PDOException $e) {
                                     
  //捕获异常--PDOException(Exception的简单重写)
     echo "数据库连接失败:".$e->getMessage();               
     //getMessage()--PDOException类中定义的方法
  }
?>

创作不易,喜欢的话加个关注点个赞,蟹蟹蟹蟹

全部评论

相关推荐

黑皮白袜臭脚体育生:简历条例统一按使用了什么技术实现了什么功能解决了问题或提升了什么性能指标来写会好些,如使用布隆过滤器实现了判断短链接是否存在,大大提升了查询速度
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务