zoukankan      html  css  js  c++  java
  • php之pdo操作

    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);
  • 相关阅读:
    c#中跨线程调用windows窗体控件
    像职业选手样编码:地道Python
    数据挖掘笔记 第一章:引言
    SVN使用教程(基于SAE)
    常用的js函数
    linux服务之tuned
    PHP 开启短标签
    如叶梦想!
    分布式控制系统Git学习
    LabVIEW(十六):多列列表框控件
  • 原文地址:https://www.cnblogs.com/Rawan/p/11973222.html
Copyright © 2011-2022 走看看