Search code examples
phpsqlmysqlicurrency

MySQLi SUM function with pound/dollar sign?


Within my Admin panel, I would like to see all profits and sales by Weekly, Monthly, Yearly and Total.

So far I am able to display the transactions recorded in the ap_payment_logs database in to an advanced responsive table. Above this is where I am trying to display the profits for each margin: Weekly, Monthly Yearly and Total. By selecting and calculating the column: txn_amount.

This all works with normal numbers added to that column, although the way my site works, it adds a Pound sign (£) before the digits:

£10.00, £20.00, £50.00...

The SUM function doesn't seem to work with this Pound sign, so I am wondering if there is any simple way to perform the same calculations which would work for this? Here is my current code:

$result = $conn->query('SELECT SUM(txn_amount) AS value_sum FROM `ap_payment_logs` WHERE `txn_date` >= NOW() - INTERVAL 7 DAY'); 
                $row = mysqli_fetch_assoc($result); 
                $sum = $row['value_sum'];
                echo $sum;

Please Note: I cannot remove the addition of the £ sign to achieve my results.

Thanks in advance!


Solution

  • Having a Table like this:

    create table dummy (
       id int primary key auto_increment, 
       test varchar(10)
    ); 
    

    and these rows in the table:

    mysql> select * from dummy;
    +----+---------+
    | id | test    |
    +----+---------+
    |  1 | 10.0    |
    |  2 | 14.0    |
    |  3 | €14.0   |
    +----+---------+
    

    you could get the sum of the test values with the following select statement:

    select sum(replace(test, '€', '')) from dummy;
    

    Anyway like Mark Baker I would recommend to store your numeric colums in numeric fields as this has a couple of advantages (aggregates like sum are easier, sorting works...).