How to manipulate data coming from the bank using PDO

1

I'm starting to use PDO in my projects in PHP. When I worked with mysql, without PDO, when I got a query in DB, I was able to get every data associated with a variable and could do what I wanted with it. Now using PDO, how can I do this data manipulation?

For example: I did this ..

$contas_entrada = mysql_query("SELECT valor FROM entrada WHERE id_empresa='$id_empresa' ORDER BY data DESC");
while($entrada_row = mysql_fetch_array($contas_entrada)){
$valor = $entrada_row['valor'];
}

So I could work on the variable $ value to tweak it. How can I get data, via PDO, to manipulate them?

    
asked by anonymous 29.10.2015 / 19:39

1 answer

1

It's not hard to convert the code:

$sql = "SELECT valor FROM entrada WHERE id_empresa = :id ORDER BY data DESC";
$stmt = $pdo->prepare($sql);
if($stmt->execute(array(':id' => $id))){
    print_r($stmt->errorInfo);
}

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

$total = 0;
foreach($itens as $item){
    $total += $item['valor'];
}

Or you can use the while / fetch () variant

$total = 0;
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    $total += $row['valor'];
}
    
29.10.2015 / 19:46