.
3ss.cn

怎么运用PHP进行数据库操作类

PHP高级实战-数据库操作类

主流php开发框架

父类(Mode1类 )

1、sql语句回顾

insert into user (name, age, money) values (' abc', 18, 1000) ;
update user set age=20, money=1500 where id=1;
delete from user where id=2;
select * from user where id=3 group by . . . having . . . order by ..limit

我们还是以代码为例,新建一个文件,定义一个class类,当我们在封装model类的时候我们需要加入成员变量,比如说主机名,用户名,密码,数据库名,字符集以及数据表前缀,接着我们连接数据库成功之后会返回一个资源,而我们需要把资源保存成成员变量,这样我们在其他地方使用的时候就非常方便了,因此我们加上数据库连接资源以及数据表名(自己可以指定表名)我们在调试数据库的时候经常会出现一些错误,因此我们调试错误都需要SQL语句,操作数组,存放的就是所有的查询条件;

具体代码如下:

<?php
class Model
{
  //主机名.
  protected $host;
  //用户名.
  protected $user;
  //密码
  protected $pwd;
  //数据库名
  protected $dbname;
 //字符集
 protected $charset;
 //数据表前缀
 protected $prefix;
 //数据库连接资源
 protected $link;
 //数据表名     这里可以自己指定表名
 protected $tableName ;
 //sql语句
 protected $sql;
 //操作数组存放的就是所有的查询条件
 protected $options;
}

因为有很多成员变量,因此我们需要对她初始化,

//filed方法

//table方法

/ /where方法

//group方法

/ /having方法

//order方法

//limit方法

,我们可以根据这些方法吧SQL语句拼接出来,只有这样我们才能实现查询。我们查询的时候需要两个方法,一个是query一个是exec方法;代码如下:

 //构造方法,对成员变量进行初始化
 function_construct()
 {
 }
我们构造完之后,上面刚刚写的代码都需要初始化,太多,我们可以传递一个数组进来,
  function_construct( $config)
  {
  //对成员变量一一进行初始化
  $this->host = $config['DB_HOST'];
  $this->user = $config['DB_USER'];
  $this->pwd = $config['DB_PWD'] ;
  $this ->dbname = $config['DB_NAME ' j;
  $this->charset = $config['DB_CHARSET'] ;
  $this->prefix = $config['DB_PREFIX'] ;
  }
  紧接着我们需要连接数据库:
  //连接数据库
  $this->link = $this ->connect();
}
protected function connect( )
{
  $link = mysqli_connect($this->host, $this->user,$this->pwd) ; .
if (!$link) {
die('数据库连接失败');
  }

//选择数据库

mysqli_select_db($link, $this->dbname);

//设置字符集

mysqli_set_charset($link, $this->charset);

//返回连接成功的资源

return $link;
 }
赞(0)
未经允许不得转载:互联学术 » 怎么运用PHP进行数据库操作类

评论 抢沙发