How to add decimals of a Mysql record with php?

0

I have a small drawback about adding up the total of a field in the database that is of type DOUBLE (6,3) .

I have dealt with number_format and money_format.

An example is when I'm going to register the field, I put 240 and when I save the value it's: 240,000, which is the result I want. But now I want to get the total sum of all the records in that field but the result does not separate it with semicolons. he gives it to me whole and that's what I do not want. What I have up to now is this:

<?php

require_once "modelo/Conectar.php";

$con=Conectar::conexion();

$sql=$con->query("select sum(monto) from prestamo");

$cons=$sql;

setlocale(LC_MONETARY, 'it_IT');
echo money_format('%.2n', $cons);
?>
    
asked by Juanzu 26.08.2017 в 02:39
source

2 answers

2

This would be a table example using DECIMAL Here 20 would represent the maximum number of digits and 3 the number of decimal digits in the field.

Create table

CREATE TABLE IF NOT EXISTS decimal_20170827 (
id INT AUTO_INCREMENT PRIMARY KEY,
descripcion VARCHAR(255),
precio DECIMAL( 20, 3 ) NOT NULL);

Insert

You would insert the data using only the decimal point, thousands separators are not necessary, since they are only used in the format.

INSERT INTO decimal_20170827(descripcion,precio)
VALUES 
('Moto', 300599.010),
('Auto Seat',1000000.999),
('Bicicleta',1000.002);

Format data in the SELECT

Let's see a SELECT with several possibilities:

SELECT  id, 
        descripcion, 
        precio, 
        FORMAT(precio, 3) as normal, 
        FORMAT(precio, 3, 'en_US') as en_US,
        FORMAT(precio, 3, 'es_ES') as es_ES 
        FROM decimal_20170827;

Doing the SELECT without any format, as is the case of the precio column, will give you the data as it is stored, without any format. The FORMAT(precio, 3) as normal will give you the data with three decimal digits, using the default format of the system. You can also apply local formats , as shown by FORMAT(precio, 3, 'en_US') and FORMAT(precio, 3, 'es_ES')

The result of the previous query would be:

Array
(
    [0] => Array
        (
            [id] => 1
            [descripcion] => Moto
            [precio] => 300599.010
            [normal] => 300,599.010
            [en_US] => 300,599.010
            [es_ES] => 300599,010
        )

    [1] => Array
        (
            [id] => 2
            [descripcion] => Auto Seat
            [precio] => 1000000.999
            [normal] => 1,000,000.999
            [en_US] => 1,000,000.999
            [es_ES] => 1000000,999
        )

    [2] => Array
        (
            [id] => 3
            [descripcion] => Bicicleta
            [precio] => 1000.002
            [normal] => 1,000.002
            [en_US] => 1,000.002
            [es_ES] => 1000,002
        )

)

Código completo: Ver Demo

<?php

/**
 * Consulta con PDO 
 * 
 * Notas: 
 * 1. Los require indicados solo sirven para este ejemplo
 * 2. La consulta  SQL y el  resultado  son sólo para mostrar  un ejemplo , 
 *    cada uno debe adaptarla  a sus necesidades
*/

require_once "dBug!.php";

require "util/public_db_info.php";

$connect = new PDO($dsn, $user_name, $pass_word);

//SQL 
$sqlCreate = 
    "CREATE TABLE IF NOT EXISTS decimal_20170827 (
    id INT AUTO_INCREMENT PRIMARY KEY,
    descripcion VARCHAR(255),
    precio DECIMAL( 20, 3 ) NOT NULL
);";    


$sqlInsert=
    "INSERT INTO decimal_20170827(descripcion,precio)
     VALUES('Moto', 300599.010),('Auto Seat',1000000.999),('Bicicleta',1000.002);";

//Enviar la consulta a la BD  usando  query->  (hay otros formas de hacerlo, ver ayuda de PHP)

$connect->query($sqlCreate);
//$connect->query($sqlInsert);


$sqlSelect=
    "SELECT id, descripcion, precio, 
            FORMAT(precio, 3) as normal, 
            FORMAT(precio, 3, 'en_US') as en_US,
            FORMAT(precio, 3, 'es_ES') as es_ES 
            FROM decimal_20170827";
$result = $connect->query($sqlSelect);


/**
 * Se crea un array asociativo  de los  resultados usando fecht-> y se almacena en $datos
 *  Hay otras formas de almacenar el  resultado según las  necesidades...
 *  Ver ayuda de PHP para  otras variantes de  fetch
*/ 
$datos = $result->fetchAll(PDO::FETCH_ASSOC);

//Se verifica que la consulta  devolvió valores
if ($datos)
{
    echo "<pre>";
    print_r($datos);
    echo "</pre>";


}else{
 print_r("No se encontraron datos, verifique su conexión o la consulta enviada");   
}

//Se cierra la conexión PDO
$connect = null;

?>

PD: The formats can also be applied using PHP if necessary.

    
answered by 26.08.2017 в 18:18
1

Try this:

SELECT ROUND(SUM(monto), 2) suma
FROM prestamo;

Confirm me if it's good for you

Greetings

    
answered by 26.08.2017 в 03:41