您的位置:首页 > 博客中心 > 数据库 >

PHP连接数据库,实现最基本的增删改查(面向对象)

时间:2022-03-10 17:16

1、创建mysql_class.php文件然后在该文件中创建Mysql类,并定义变量

<?php     class Mysql{         private $host;//服务器地址         private $root;//用户名         private $password;//密码         private $database;//数据库名                   //后面所提到的各个方法都放在这个类里         //...     } ?>

2、通过构造函数初始化类

function __construct($host,$root,$password,$database){     $this->host = $host;     $this->root = $root;     $this->password = $password;     $this->database = $database;     $this->connect(); }

对于connect()方法,下一步再说

3、创建连接数据库及关闭数据库方法

function connect(){     $this->conn = mysql_connect($this->host,$this->root,$this->password) or die("DB Connnection Error !".mysql_error());     mysql_select_db($this->database,$this->conn);     mysql_query("set names utf8"); }           function dbClose(){     mysql_close($this->conn); }

4、对mysql_query()、mysql_fetch_array()、mysql_num_rows()函数进行封装

function query($sql){     return mysql_query($sql); }          function myArray($result){     return mysql_fetch_array($result); }          function rows($result){     return mysql_num_rows($result); }

5、自定义查询数据方法

function select($tableName,$condition){     return $this->query("SELECT * FROM $tableName $condition"); }

6、自定义插入数据方法

function insert($tableName,$fields,$value){     $this->query("INSERT INTO $tableName $fields VALUES$value"); }

7、自定义修改数据方法

function update($tableName,$change,$condition){     $this->query("UPDATE $tableName SET $change $condition"); }

8、自定义删除数据方法

function delete($tableName,$condition){     $this->query("DELETE FROM $tableName $condition"); }

现在,数据库操作类已经封装好了,下面我们就来看看该怎么使用。

我们用的还是在PHP连接数据库,实现最基本的增删改查(面向过程)一文中所涉及到的数据库及表(表中数据自己添加):

gxlsystem.com,布布扣

9、那么我们先对数据库操作类进行实例化

$db = new Mysql("localhost","root","admin","beyondweb_test");

实例化可以在mysql_class.php文件中的Mysql类之外进行。

然后我们再创建一个test.php文件,首先把mysql_class.php文件引入

<?php     require("mysql_class.php"); ?>

然后我们就开始操作吧

10、向表中插入数据

<?php     $insert = $db->insert("user","(nikename,email)","(#beyondweb#,#beyondwebcn@xx.com#)");//请把#号替换为单引号     $db->dbClose(); ?>

11、修改表中数据

<?php     $update = $db->update("user","nikename = #beyondwebcn#","where id = #2#");//请把#号替换为单引号     $db->dbClose(); ?>

12、查询表中数据并输出

<?php     $select = $db->select("user");     $row = $db->rows($select);     if($row>=1){ ?> <table border="1px">     <tr>         <th>id</th>         <th>nikename</th>         <th>email</th>     </tr> <?php     while($array = $db->myArray($select)){         echo "<tr>";         echo "<td>".$array[#id#]."</td>";//请把#号替换为单引号         echo "<td>".$array[#nikename#]."</td>";//请把#号替换为单引号         echo "<td>".$array[#email#]."</td>";//请把#号替换为单引号         echo "</tr>";     } ?> </table> <?php     }else{         echo "查不到任何数据!";     }            $db->dbClose(); ?>

13、删除表中数据

<?php     $delete = $db->delete("user","where nikename = #beyondweb#");//请把#号替换为单引号     $db->dbClose(); ?>

PHP连接数据库,实现最基本的增删改查(面向对象),布布扣,bubuko.com

热门排行

今日推荐

热门手游