首页 > 代码库 > php编写mysql操作类
php编写mysql操作类
文件:mysql.class.php<?phperror_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 <?phpinclude "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);?>
php编写mysql操作类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。