您的位置:首页 > 编程语言 > PHP开发

在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表。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php mysql 函数