-1

listed with numerical values in my table, i'm trying to insert cummulative values through php to mysql table. so that i can fetch them easily using select query for later uses.

I'm trying to figure out a php script which can insert values into this table (dmatrix), tried mysql variables but failed to send them/ insert into mysql table Expected output:

id | datac |Cummulative   
1  | 200   | 200    
2  | 300   | 500  
3  | 400   | 900  
4  | 500   | 1400

Thanks in advance. please help me out friends

Mr. Radical
  • 1,847
  • 1
  • 19
  • 29
  • 1
    possible duplicate of [Create a Cumulative Sum Column in MySQL](http://stackoverflow.com/questions/2563918/create-a-cumulative-sum-column-in-mysql) – Seth Battin Feb 15 '14 at 22:41
  • You can accomplish this with a query without saving the data in a column. [This question's answers (your question is also a duplicate)](http://stackoverflow.com/a/2563940/1004027) provide a good method to calculate it on the fly. Let the DB do its job, instead of bogging it down with manually aggregated data that can get stale. – Seth Battin Feb 15 '14 at 22:44

1 Answers1

0

I'm going to make a few assumptions:

  • I will assume you are using a PDO object to communicate with your MySQL database from your PHP script.
  • I will assume that the id column in the dmatrix table is auto-incrementing.

With those assumptions, the code will look like this:

<?php

$datac = $_POST['datac'];

$sql = '
    INSERT INTO dmatrix (datac, Cummulative)
    SELECT :datac1, :datac2 + IFNULL(SUM(datac), 0)
    FROM dmatrix
';

$stmt = $dbh->prepare($sql);
$stmt->bindValue(':datac1', $value, PDO::PARAM_INT);
$stmt->bindValue(':datac2', $value, PDO::PARAM_INT);
$stmt->execute();
Shaunak Kashyap
  • 598
  • 3
  • 6
  • I think if you think of `$values` in the above code as the `datac` input from a HTML form, the above code should work. Nevertheless, if you could you share the HTML code that takes inputs for 'datac', that might make things clearer. – Shaunak Kashyap Feb 16 '14 at 15:39
  • hi shaunak i'm positng my html code php script should fetch the datac and perform cummulative function and it must insert into my table dmatrix CODE :->
    Input Data: Area  pincode: Agency: > Data count
    – user2389346 Feb 16 '14 at 15:44
  • hi shaunak i have got a error of using $dbh later i have solved it but again i'm hit with this ERROR :-> Call to a member function bindValue() on a non-object – user2389346 Feb 16 '14 at 23:01
  • when user enters a value in one text field(html) using this value php code must insert cummulative values into the cummulative coloumn which is shown in figure. thanks for your patience shaunak – user2389346 Feb 16 '14 at 23:41