pranatayudha pranatayudha - 3 years ago 110
PHP Question

How to: MySQLi to PDO

I have code that uses MySQLi for access to the database and I want to change to PDO Statement, anyone can help? There's my code:

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;
}

Answer Source
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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download