在PHP中封装MySQL常用函数
2017-01-06 16:15
357 查看
<?php function connect(){ $link = mysql_connect("localhost","root","")or die("链接失败".mysql_errno().":".mysql_error()); mysql_set_charset("utf8"); mysql_select_db("shop") or die("false"); return $link; } connect(); function insert($table,$array){ $keys=join(",",array_keys($array)); $vals="'".join("','",array_values($array))."'"; $sql="insert {$table}($keys) values({$vals})"; mysql_query($sql); return mysql_insert_id().$sql; } /* $arr=array('aId'=>"02",'aName'=>"ac",'aPw'=>"000",'aEm'=>"1433@qq.com"); $ta = "admin"; $in=insert($ta,$arr); print_r($in); */ function update($table,$array,$where = null){ $str = null; foreach($array as $key => $val){ if($str == null){ $sep = ""; }else{ $sep = ","; } $str.=$sep.$key."='".$val."'"; } $sql1 = "update {$table} set {$str} ".($where == null?null:" where ".$where); $result = mysql_query($sql1); print_r($sql1); if($result){ return mysql_affected_rows(); }else{ return false; } } /* $arr1 = array('aName'=>"c66b",'aPw'=>"7yy"); $ta = "admin"; $wh = "aId = 02"; $up = update($ta,$arr1,$wh); */ function delete($table,$where = null){ $sql = "delete from {$table} " .($where == null?null:" where ".$where); mysql_query($sql); return mysql_affected_rows(); } /* $ta = "admin"; $wh = "aId = 02"; $up = delete($ta,$wh); */ function fetchOne($sql,$result_type=MYSQL_ASSOC){ $result=mysql_query($sql); $row=mysql_fetch_array($result,$result_type); return $row; } function fetchAll($sql,$result_type=MYSQL_ASSOC){ $result=mysql_query($sql); while(@$row=mysql_fetch_array($result,$result_type)){ $rows[]=$row; } return $rows; } $sql = "select * from admin"; $r=fetchAll($sql,$result_type=MYSQL_ASSOC); print_r($r);
注:测试数据库参照博文数据库shop中admin表。
相关文章推荐
- 一个关于if else容易迷惑的问题
- MySQL中的integer 数据类型
- MySQL存储过程
- PHP5.2.*防止Hash冲突拒绝服务攻击的Patch
- 深入理解PHP之匿名函数
- mysql中int、bigint、smallint 和 tinyint的区别与长度
- mysql load data 导出、导入 csv
- source命令执行SQL脚本文件
- JSP/PHP基于Ajax的分页功能实现
- MySQL创建用户及权限控制
- MySQL管理数据表
- linux下mysql添加用户
- mysql procedure
- mysql触发器
- 关于PHP通过PDO用中文条件查询MySQL的问题。
- 解决mysql 开启logbin 导致存储过程报错
- 什么是设计模式