How to add a database column using PDO

Asked

Viewed 1,602 times

2

Good evening everyone. I have little experience in programming. I apologize if I am not very clear on the question.

I have a Mysql database (phpmyadmin) with a table named "my table" having one of the fields named "value". I need to add the "value" field of all rows in the table.

To count the amount of data worked when I used the following excerpt:

$select = $pdo->query("SELECT * FROM minha_tabela")->fetchAll();

// atribuindo a quantidade de linhas retornadas
$count = count($select);

// imprimindo o resultado
print $count;

Now I have to add up and I don’t know how to write the program. I am using PDO programming. Thank you very much.

  • 1

    If it’s just a count, use SELECT COUNT(*) FROM minha_tabela instead of this count($select), so you have a result line with the value. This is what you’ve done by moving the entire table from Mysql to PHP just to get a count, which is unthinkable in a normal application (unless you’re going to use all the data right away).

3 answers

3


Use the following SQL query:

SELECT SUM(valor) AS total FROM minha_tabela

See more details on how to use SUM here.

Then in the PDO you do this:

$soma = $pdo->query("SELECT SUM(valor) AS total FROM minha_tabela")->fetchColumn();

// Imprimindo o resultado.
print $soma;
  • 1

    Hello Victor Stafusa. Thank you so much for your answer. I just tested it and it really worked. Know that it helped me a lot. A big hug. and Thank you to all who have dedicated themselves to understanding my question.

  • 1

    @Jorgepeinado If my answer has served you, be sure to mark it as correct/accept by clicking on the green side here. Thank you. :)

  • 1

    Hello Victor Stafusa. Thank you so much for your answer. I just tested it and it really worked. Know that it helped me a lot. A big hug. and Thank you to all who have dedicated themselves to understanding my question.

0

$stmt = new PDO("mysql:host={$servername};dbname={$dbname}",$username, $password);
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$soma = $stmt->query("SELECT SUM(valor) as total FROM nome_tabela")->fetchColumn();
//imprime com as pontuação e virgula
print number_format($soma, 2, ",",".");

0

$soma = $pdo->query("SELECT SUM(valor) AS total FROM minha_tabela")->fetchColumn();
print number_format($soma, 2, ",",".");

It saved a whole afternoon’s work!!!!

Thank you

Browser other questions tagged

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