php编写mysql操作类
文件:mysql.class.php <?php error_reporting(E_ALL ^ E_DEPRECATED); /* mysql操作类 * 1.连接数据库 * 2.选择需要操作的库 * 3.设置操作的编码 * 4.增删改查 * 查询分两种情况: * 1.查询一条数据:执行一次mysql_fetch_assoc * 2.查询多跳数据:执行多次mysql_fetch_assoc * 5.关闭数据库 */ class mysql { public $hostname; //mysql主机 public $username; //mysql用户名 public $password; //mysql密码 public $conn; //连接标识符 public $dbname; //操作的数据库名 public $charset; //操作编码 //初始化 function __construct($hostname,$username,$password,$dbname,$charset) { $this->hostname = $hostname; $this->username = $username; $this->password = $password; $this->dbname = $dbname; $this->charset = $charset; //曾经的方式 //连接数据库 $this->conn = mysql_connect($this->hostname,$this->username,$this->password); //选择操作的数据库 mysql_select_db($this->dbname,$this->conn); //现在的方式,连接数据库并选择操作的数据库 //$this->conn = mysqli_connect($this->hostname,$this->username,$this->password,$this->dbname) //or die(mysql_error()); //3.设置操作的编码 $this->query("set names ‘".$this->charset."‘"); } //执行SQL语句的方法 function query($sql){ return mysql_query($sql,$this->conn); } //添加 function add($table,$set){ $sql = "insert into {$table} set {$set}"; $result=$this->query($sql); return $result; } //修改 function edit($table,$set,$where){ $sql = "update {$table} set {$set} where {$where}"; $result = $this->query($sql); return $result; } //删除 function del($table,$where){ $sql = "delete from {$table} where {$where}"; $result = $this->query($sql); return $result; } //查询一条数据 function find($table,$where="",$fields="*",$order=""){ $where = empty($where) ? "": " where ".$where; $order = empty($order) ? "": " order by ".$order; //$limit = empty($limit) ? "": " limit ".$limit; $sql = "select {$fields} from {$table} {$where} {$order} limit 1 "; $query = $this->query($sql); $row = mysql_fetch_assoc($query); return $row; } //查询多条数据 function select($table,$where="",$fields="*",$order="",$limit=""){ $where = empty($where) ? "": " where ".$where; $order = empty($order) ? "": " order by ".$order; $limit = empty($limit) ? "": " limit ".$limit; $sql = "select {$fields} from {$table} {$where} {$order} {$limit} "; $query = $this->query($sql); $result = array(); while($row = mysql_fetch_assoc($query)){ //将$row的值添加到$result的数组中去 $result[] = $row; } return $result; } //回收资源 function __destruct(){ mysql_close($this->conn); } } ?> 文件2: ceshi.php <?php include "mysql.class.php"; $db= new mysql("localhost","root","","test","GBK"); //执行添加 //$db->add("test","id=‘‘,uid=‘sky‘,regdate=now(),remark=‘student1‘"); //执行修改 //$db->edit("test","id=‘23‘,uid=‘nono‘,regdate=now(),remark=‘程序员‘","id=‘22‘"); //执行删除 //$db->del("test","id=‘23‘"); //执行查找 //$rs= $db->find("test","id=3","uid,remark","desc"); //print_r($rs); //执行多条查找 $rs = $db->select("test"); print_r($rs); ?>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。