单例模式封装MyPDO类

文章提供了一个PHP类`MyPDO`,实现了数据库操作的单例模式,包括初始化参数、连接数据库、执行增删改查操作以及异常处理。类中包含了数据操作的部分,如执行SQL语句、获取自动增长的ID,以及数据查询部分,如获取二维数组、一维数组和一行一列的数据。
摘要由CSDN通过智能技术生成

步骤

1、单例模式

2、初始化参数

3、连接数据库

4、执行增删改

5、执行查询

   a)返回二维数组

   b)返回一维数组

   c)返回一行一列

代码实现

第一部分:单例、初始化参数、实例化PDO

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

<?php

class MyPDO{

    private $type;      //数据库类别

    private $host;      //主机地址

    private $port;      //端口号

    private $dbname;    //数据库名

    private $charset;   //字符集

    private $user;      //用户名

    private $pwd;       //密码

    private $pdo;       //保存PDO对象

    private static $instance;

    private function __construct($param) {

        $this->initParam($param);

        $this->initPDO();

    }

    private function __clone() {

    }

    public static function getInstance($param=array()){

        if(!self::$instance instanceof self)

            self::$instance=new self($param);

        return self::$instance;

    }

    //初始化参数

    private function initParam($param){

        $this->type=$param['type']??'mysql';

        $this->host=$param['host']??'127.0.0.1';

        $this->port=$param['port']??'3306';

        $this->dbname=$param['dbname']??'data';

        $this->charset=$param['charset']??'utf8';

        $this->user=$param['user']??'root';

        $this->pwd=$param['pwd']??'root';

    }

    //初始化PDO

    private function initPDO(){

        try{

            $dsn="{$this->type}:host={$this->host};port={$this->port};dbname={$this->dbname};charset={$this->charset}";

            $this->pdo=new PDO($dsn$this->user, $this->pwd);

        catch (PDOException $ex) {

            echo '错误编号:'.$ex->getCode(),'<br>';

            echo '错误行号:'.$ex->getLine(),'<br>';

            echo '错误文件:'.$ex->getFile(),'<br>';

            echo '错误信息:'.$ex->getMessage(),'<br>';

            exit;

        }

    }

}

//测试

$param=array(

);

$mypdo= MyPDO::getInstance($param);

var_dump($mypdo);

第二部分:数据操作部分

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

<?php

class MyPDO{

    private $type;      //数据库类别

    private $host;      //主机地址

    private $port;      //端口号

    private $dbname;    //数据库名

    private $charset;   //字符集

    private $user;      //用户名

    private $pwd;       //密码

    private $pdo;       //保存PDO对象

    private static $instance;

    private function __construct($param) {

        $this->initParam($param);

        $this->initPDO();

        $this->initException();

    }

    private function __clone() {

    }

    public static function getInstance($param=array()){

        if(!self::$instance instanceof self)

            self::$instance=new self($param);

        return self::$instance;

    }

    //初始化参数

    private function initParam($param){

        $this->type=$param['type']??'mysql';

        $this->host=$param['host']??'127.0.0.1';

        $this->port=$param['port']??'3306';

        $this->dbname=$param['dbname']??'data';

        $this->charset=$param['charset']??'utf8';

        $this->user=$param['user']??'root';

        $this->pwd=$param['pwd']??'root';

    }

    //初始化PDO

    private function initPDO(){

        try{

            $dsn="{$this->type}:host={$this->host};port={$this->port};dbname={$this->dbname};charset={$this->charset}";

            $this->pdo=new PDO($dsn$this->user, $this->pwd);

        catch (PDOException $ex) {

            $this->showException($ex);

            exit;

        }

    }

     

    //显示异常

    private function showException($ex,$sql=''){

        if($sql!=''){

            echo 'SQL语句执行失败<br>';

            echo '错误的SQL语句是:'.$sql,'<br>';

        }

        echo '错误编号:'.$ex->getCode(),'<br>';

        echo '错误行号:'.$ex->getLine(),'<br>';

        echo '错误文件:'.$ex->getFile(),'<br>';

        echo '错误信息:'.$ex->getMessage(),'<br>';

    }

    //设置异常模式

    private function initException(){

        $this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

    }

    //执行增、删、改操作

    public function exec($sql){

        try{

            return $this->pdo->exec($sql);

        catch (PDOException $ex) {

            $this->showException($ex$sql);

            exit;

        }

    }

    //获取自动增长的编号

    public function lastInsertId(){

        return $this->pdo->lastInsertId();

    }

}

//测试

$param=array(

    

);

$mypdo= MyPDO::getInstance($param);

//echo $mypdo->exec('delete from news where id=6');

if($mypdo->exec("insert into news values (null,'11','1111',unix_timestamp())"))

    echo '自动增长的编号是:'.$mypdo->lastInsertId ();

第三部分:数据查询部分

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

<?php

class MyPDO{

   ...

     

    //判断匹配的类型

    private function fetchType($type){

        switch ($type){

            case 'num':

                return PDO::FETCH_NUM;

            case 'both':

                return PDO::FETCH_BOTH;

            case 'obj':

                return PDO::FETCH_OBJ;

            default:

                 return PDO::FETCH_ASSOC;

        }

    }

    //获取所有数据 ,返回二维数组

    public function fetchAll($sql,$type='assoc'){

        try{

            $stmt=$this->pdo->query($sql);  //获取PDOStatement对象

            $type$this->fetchType($type); //获取匹配方法

            return $stmt->fetchAll($type);

        catch (Exception $ex) {

            $this->showException($ex$sql);

        }

    }

    //获取一维数组

    public function fetchRow($sql,$type='assoc'){

        try{

            $stmt=$this->pdo->query($sql);  //获取PDOStatement对象

            $type$this->fetchType($type); //获取匹配方法

            return $stmt->fetch($type);

        catch (Exception $ex) {

            $this->showException($ex$sql);

            exit;

        }

    }

    //返回一行一列

    public function fetchColumn($sql){

        try{

             $stmt=$this->pdo->query($sql);

            return $stmt->fetchColumn();

        catch (Exception $ex) {

            $this->showException($ex$sql);

            exit;

        }

         

    }

     

}

//测试

$param=array(

    

);

$mypdo= MyPDO::getInstance($param);

//echo $mypdo->exec('delete from news where id=6');

/*

if($mypdo->exec("insert into news values (null,'11','1111',unix_timestamp())"))

    echo '自动增长的编号是:'.$mypdo->lastInsertId ();

 */

//$list=$mypdo->fetchAll('select * from news');

//$list=$mypdo->fetchRow('select * from news where id=1');

$list=$mypdo->fetchColumn('select count(*) from news');

echo '<pre>';

var_dump($list);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执刀人的工具库

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值