How to manipulate data from the database using PDO

Asked

Viewed 1,304 times

1

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

For an example: I would do that..

$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'];
}

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

1 answer

1


It is not difficult 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'];
}
  • All right, I’ll try @rray. My other question, I haven’t found a solution yet. Do you have an email for us? Abs.

  • i got used to doing the query, like this: $pegaData=$Pdo->prepare("SELECT data FROM input WHERE id_input=:id"); $pegaData->bindValue(":id", 30); How can I get the date from here?

  • $pegaData=$pdo->prepare("SELECT data FROM entrada WHERE id_entrada=:id");
$pegaData->bindValue(":id", 30);
$pegaData->execute();
$res = $pegaData->fetchAll(PDO::FETCH_ASSOC);
print_r($res); @Gustavosevero

  • Now appeared... "Array ( [0] => Array ( [date] => 2014-05-05 ) - Light Bill - 50.00"

  • @Gustavosevero, it means it worked! : D. Use the fetchAll() when you know that the query will return several lines and fetch() when return only one line.

  • All right, I’ll check it out.

  • Perfect, I got it. Thanks. Give me your email?

  • @Gustavosevero, step just wait for me to get home

  • Of course! Hehehehehehe

  • @Gustavosevero ta ai?

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.