Error in Ajax with query Mysqli

0

I am trying to recover some data from , add them and show them by means of a query

Javascript

$(function () {
 $("#previousdate").on("click",function(){
   $.ajax({
    type: "POST",
    url: base_url + 'index.php/welcome/showVentas',
    data:{
        'fecha' : $("#dateindex").val(),
    },
    success:function(e){
         alert(e);
    },
    error:function(e){
        alert("error");
    }
  });
 }
});

php:

function showVentas()
{
    $fecha = $_POST['fecha'];

    $fecha2 = explode("/", $fecha);
    $inicio = $fecha2[2] . "-" . $fecha2[1] . "-" . $fecha2[0] . " 00:00:00";
    $fin    = $fecha2[2] . "-" . $fecha2[1] . "-" . $fecha2[0] . " 23:59:59";

    $statement = "SELECT cash FROM pr_gadgets_information WHERE created <= '$fin' && created >= '$inicio'";

    $query     = $this->db->query($statement);

    $result = 0;

    while ($fila = $query->fetch_assoc())
    {
        $result += $fila['cash'];
    }
    echo $result;


}

I think the error is in my function

asked by Korzan 19.04.2017 в 20:55
source

2 answers

0

The problem was in the php part, because of using codeigniter I can not use:

while ($fila = $query->fetch_assoc())
{
    $result += $fila['cash'];
}
echo $result;

I have to use:

foreach ( $query->result_array() as $row)
{
   $result += $row['cash'];

}

echo $result;

With that change works perfectly, thanks for your answers

    
answered by 20.04.2017 / 12:12
source
1

You execute the query but you are not recovering the results it brings.

It would also add a date-to-date validation, you should escape the data or use prepared statements to avoid SQL injection.

function showVentas()
{
    $fecha = $_POST['fecha'];

    /* Validamos la fecha */
    // dd/mm/aaaa --> 11/01/2015
    $expresion_regular_fecha='/^([0][1-9]|[12][0-9]|3[01])(\/|-)([0][1-9]|[1][0-2])(\d{4})$/'; 
    if (!preg_match($expresion_regular_fecha, $fecha))
    {
        return 'La fecha no es válida';
    }


    $fecha2 = explode("/", $fecha);
    $inicio = $fecha2[2] . "-" . $fecha2[1] . "-" . $fecha2[0] . " 00:00:00";
    $fin    = $fecha2[2] . "-" . $fecha2[1] . "-" . $fecha2[0] . " 23:59:59";

    $statement = "SELECT cash as total FROM pr_gadgets_information WHERE created <= '$fin' && created >= '$inicio'";

    $query     = $this->db->query($statement);

    $result = 0;

    /* despues de realizar la consulta necesitas traer los resultados */
    while ($fila = $query->fetch_assoc())
    {
        $result += $fila['cash'];
    }

    /*
    foreach ($query as $row)
    {
        $result = $result + $row['cash'];
    }
    */

    echo $result;


}

I also think that if you just want to get the sum of the records you could do it with the SUM function () of SQL directly.

    
answered by 19.04.2017 в 21:21