在PHP中封装MySQL常用函数

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)