Add mysql row values

Discussion in 'PHP' started by emi87, Jun 18, 2010.

  1. #1
    Hello,

    I have a table with two fields: id , pieces
    If table has some rows the id will be 1, 2, 3, 4 etc. and pieces will be for example(2342, 543634, 52543, 34, etc.)
    I want in a variable $total_pieces to put the number of all pieces (piece from row 1 + piece from row 2 + etc.)
    How can I do this?
    I don't know the total number of pieces. Maybe there will be 1000 pieces.

    Please help!
    Thank you!
     
    emi87, Jun 18, 2010 IP
  2. Cozmic

    Cozmic Member

    Messages:
    146
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    48
    #2
    
    // Initiate variables.
    $total_pieces = 0;
    
    // Query database. Make sure to put in your table name.
    $query = mysql_query("SELECT * FROM `tableName`");
    
    // Loops over result
    while ($row = mysql_fetch_array($query)) {
       // Preforms addition.
       $total_pieces = $total_pieces + $row['pieces'];
    }
    PHP:
     
    Cozmic, Jun 18, 2010 IP
  3. emi87

    emi87 Peon

    Messages:
    49
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    This works great!
    Thank you very much Cozmic!
     
    emi87, Jun 18, 2010 IP