Add php and SQL server

5

Hi, I'm working php with sql server and I need some help with the following:

I have this query

$sql = "select saldo_final from cuentas where doc = '1098788811'";

$consulta = sqlsrv_query($conn, $sql);

while($datos = sqlsrv_fetch_array($consulta, SQLSRV_FETCH_NUMERIC))
{
     print_r($datos);
}

The fact is that it brings me the following results

Array ( [0] => 12492.0000 ) Array ( [0] => 4006.0000 ) Array ( [0] => 4094.0000 )

What I need is to take those 3 values by php and add them

    
asked by The_pacha 27.07.2018 в 00:02
source

2 answers

3

If you want to do it in php:

$suma = 0;
while($datos = sqlsrv_fetch_array($consulta, SQLSRV_FETCH_NUMERIC))
{
     print_r($datos);
     $suma += $datos['saldo_final'];
}

If you want to do it in sql:

$sql = "select SUM(saldo_final) from cuentas where doc = '1098788811'";
    
answered by 27.07.2018 / 00:06
source
0

@alanfcm

Hi, thanks for the reply The query stayed like this, remove the

SQL_FETCH_NUMERIC

to be able to call the field "balance_final" because putting it only brings me an array of numeric indexes

$suma = 0;
while($datos = sqlsrv_fetch_array($consulta))
{
    print_r($datos);
    $suma += $datos['saldo_final'];
    echo $suma;
}

this brings me the following

Array ( [0] => 12492.0000 [saldo_final] => 12492.0000 ) 12492Array ( [0] => 4006.0000 [saldo_final] => 4006.0000 ) 16498Array ( [0] => 4094.0000 [saldo_final] => 4094.0000 ) 20592

At the end I can see the answer that is 20592, the problem is that if I remove the

print_r($datos);

Bring me the following

124921649820592

that technically is fine, what shows me there is 12492 that is the first data obtained, then it shows me 16498 that is the result of that first data added with the second, the last one brings me 20592 which is the final result, and I just want that data, the end

    
answered by 27.07.2018 в 16:51