php封装一个链接数据库的函数(增删改查)

1。我们封装一个简单的数据库的增删改查函数,方便使用

我们先写一个config文件来使用里面是你数据库的信息

接下来我们写个看封装好的函数:

 $value) {
        $value = parseValue($value);

        if (is_scalar($value)) {
            $set[] = $key . '=' . $value;
        }
    }

    return $set;
}



function del($link , $table , $where)
{
    //delte from $table where $wehre;

    $sql = "delete from $table where $where ";

    $result = mysqli_query($link , $sql);

    if ($result && mysqli_affected_rows($link)) {
        //return mysqli_insert_id($link);
        return mysqli_affected_rows($link);
    } else {
        return false;
    }
}


function select($link , $table , $where , $fields = '*')
{
    $sql = "select $fields from $table where $where";

    $result = mysqli_query($link , $sql);

    if ($result && mysqli_affected_rows($link)) {

        while ($rows = mysqli_fetch_assoc($result)) {
            $data[] = $rows;
        }
        return $data;
    } else {
        return false;
    }

}

//$data = select($link , 'bbs_user' , 'id>40');

//var_dump($data);

function sum($link , $table , $fields = 'id')
{
    $sql = "select sum($fields) as sum from $table";

    $result = mysqli_query($link , $sql);

    $sum = mysqli_fetch_assoc($result);

    return $sum['sum'];
}


//echo sum($link , 'bbs_user');
function MyMax($link , $table , $fields = 'id')
{
    $sql = "select max($fields) as max from $table";

    $result = mysqli_query($link , $sql);

    $max = mysqli_fetch_assoc($result);

    return $max['max'];
}
//echo MyMax($link , 'bbs_user');

function MyCount($link , $table , $fields = 'id')
{
    $sql = "select count($fields) as count from $table";

    $result = mysqli_query($link , $sql);

    $count = mysqli_fetch_assoc($result);

    return $count['count'];
}

//echo MyCount($link , 'bbs_user');

function MyAvg($link , $table , $fields = 'id')
{
    $sql = "select avg($fields) as avg from $table";

    $result = mysqli_query($link , $sql);

    $avg = mysqli_fetch_assoc($result);

    return $avg['avg'];
}
//求最小值
function MyMin($link,$table,$fields = 'id'){
    $sql = "select min($fields) as min from $table";
    $result = mysqli_query($link,$sql);
    $min = mysqli_fetch_assoc($result);

    return $min['min'];
}

//封装一个分组的方法

function group($link,$table,$fields = "id",$group = "province"){
    $sql = "select count($fields) as a from $table group by $group";
    var_dump($sql);
    $result = mysqli_query($link,$sql);
    if($result && mysqli_affected_rows($link)){
        while($arr = mysqli_fetch_assoc($result)){
                $arrsy[] = $arr['a'];
        }
        return $arrsy;
    }else{
        return false;
    }

}

4.我们这里写个公共类来存放,方便以后开发

    

你可能感兴趣的:(php)