如何:MySQLi到PDO

时间:2017-07-26 06:48:43

标签: php mysqli pdo

我有使用MySQLi访问数据库的代码,我想更改为PDO语句,任何人都可以提供帮助吗?这是我的代码:

function select_data($user_id, $start_date, $end_date)
{
    global $connection;

    $sql = "SELECT * FROM attendancy
        WHERE user_id = $user_id
        AND date >= '$start_date'
        AND date <= '$end_date'";

    $result = $connection->query($sql);
    if(!is_object($result)) return array();

    $data = array();

    while($row = $result->fetch_assoc())
    {
        $row['duration'] = count_work_hours($row);
        $data[] = $row;
    }

    return $data;
}

1 个答案:

答案 0 :(得分:0)

function select_data($user_id, $start_date, $end_date)
{
    global $connection;

    $sql = "SELECT * FROM attendancy
        WHERE user_id = :user_id
        AND date >= :start_date
        AND date <= :end_date";

    $stmt = $connection->prepare($sql,[PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);

    $stmt->execute([":user_id" => $user_id, ":start_date" => $start_date, ":end_date" => $end_date]);

    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);        

    if(!count($results)){
        return array();
    }
    else{

        $data = array();

        foreach($results as $row){

            $row['duration'] = count_work_hours($row);
            $data[] = $row;
        }
    }

    return $data;
}