PDO code optimization [closed]

-2

Hello, I am studying a way to increment a value before saving to the database but I need help, searching in Google for parts I was able to assemble the code and yes it works, its objective is to update a value in the database, but I'm finding the code confusing could anyone help me?

<?php

try{
$id = 1;

$pdo = new PDO("mysql:host=localhost;dbname=isbn_db", "root", "");

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//busca no banco de dados
$stmt2 = $pdo->prepare("SELECT * FROM isbn ORDER BY numero_isbn"); 
$stmt2->execute();

//fecAll busca todos os resultados
$results = $stmt2->fetchALL(PDO::FETCH_ASSOC);
//BUSCA O VALOR NO BANCO DE DADOS 
foreach ($results as $value){
    $var = $value['numero_isbn'];   
}    

//incrementa o valor obtido no banco
$var = $var + 10000000000;   

$stmt = $pdo->prepare('UPDATE isbn SET numero_isbn = :numero_isbn WHERE id = :id');
$stmt->execute(array(
    ':id' => $id,
    ':numero_isbn' => $var
));

// echo $stmt->rowCount();

echo "ISBN: ".$var;

}catch(PDOException $e){
    echo 'Error: '. $e->getMessage();
    echo "ERRO";
}

?>
    
asked by anonymous 24.11.2018 / 02:47

1 answer

1
Many programmers (including me a few years ago) would do the following to add a value to a column in the database:

  • A Select to get the current quantity
  • Adding the value
  • Finally an Update to update column
  

There is a faster and more accurate way to do this.

    SET numero_isbn = numero_isbn + :numero_isbn

PDO PHP code optimization

$id = 1;
$var=10000000000;

$pdo = new PDO("mysql:host=localhost;dbname=isbn_db", "root", "");

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

stmt = $pdo->prepare('UPDATE isbn SET numero_isbn = numero_isbn + :numero_isbn WHERE id = :id');
$stmt->execute(array(
    ':id' => $id,
    ':numero_isbn' => $var
));
    
25.11.2018 / 00:01