Change the result when two equal values are introduced to the same variable in PHP

0

I have a variable $ description in which the name of the product that is loaded is stored. What I want is that when this variable is entered a product name that already exists add the amounts of both the new and the one that is already entered. I have the following code but it does not return any value to me.

            include('is_logged.php');//Archivo verifica que el usario que intenta acceder a la URL esta logueado
/* Connect To Database*/
require_once ("../config/db.php");//Contiene las variables de configuracion para conectar a la base de datos
require_once ("../config/conexion.php");//Contiene funcion que conecta a la base de datos

$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if (isset($_GET['codigo'])){
    $codigo=intval($_GET['codigo']);


    $query=mysqli_query($con, "select * from comprobante where codigo='".$codigo."'"); 




    $count=mysqli_num_rows($query);
    if ($count==0){
        if ($delete1=mysqli_query($con,"DELETE FROM comprobante WHERE codigo='".$codigo."'")){
        ?>
        <div class="alert alert-success alert-dismissible" role="alert">
          <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <strong>Aviso!</strong> Datos eliminados exitosamente.
        </div>
        <?php 
    }else {
        ?>
        <div class="alert alert-danger alert-dismissible" role="alert">
          <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <strong>Error!</strong> Lo siento algo ha salido mal intenta nuevamente.
        </div>
        <?php

    }

    } else {
        if ($count==1){
        if ($delete2=mysqli_query($con,"DELETE FROM comprobante WHERE codigo='".$codigo."'")); }
        ?>
        <div class="alert alert-success alert-dismissible" role="alert">
          <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <strong></strong> datos eliminados exitosamente 
        </div>
        <?php
    }



}



if($action == 'ajax'){
    // escaping, additionally removing everything that could be (html/javascript-) code
     $q = mysqli_real_escape_string($con,(strip_tags($_REQUEST['q'], ENT_QUOTES)));

     $id_tipo =intval($_REQUEST['id_tipo']);


     $aColumns = array('numero_comprobante');  
     $sTable = "comprobante";
     $sWhere = "";


     $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            $sWhere .= $aColumns[$i]." LIKE '%".$q."%' OR ";
        }
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ')';

    if ($id_tipo>0){
        $sWhere .=" and id_tipo='$id_tipo'";
    }




    $sWhere.=" order by codigo desc";
    include 'pagination.php'; //include pagination file
    //pagination variables
    $page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
    $per_page = 10; //how much records you want to show
    $adjacents  = 4; //gap between pages after number of adjacents
    $offset = ($page - 1) * $per_page;
    //Count the total number of row in your table*/
    $count_query   = mysqli_query($con, "SELECT count(*) AS numrows FROM $sTable  $sWhere");
    $row= mysqli_fetch_array($count_query);




    $numrows = $row['numrows'];
    $total_pages = ceil($numrows/$per_page);
    $reload = './comprobantes.php';
    //main query to fetch the data
    $sql="SELECT * FROM  $sTable $sWhere LIMIT $offset,$per_page";
    $query = mysqli_query($con, $sql);



    //loop through fetched data
    if ($numrows>0){

        ?>
        <div class="table-responsive">
          <table class="table">
            <tr  class="success">


                <th>Numero de comprobante</th>
                <th>Descripcion</th>
                <th>Precio</th>
                <th>Cantidad</th>
                <th>Total</th>
                <th>Fecha</th>
                <th>Tipo</th>
                <th>Stock</th>
                <th>Compra</th>
                <th>Venta</th>
                <th>Utilidad</th>

                <th class='text-right'>Acciones</th>

            </tr>
            <?php
            $orden_pago=$id_tipo==1;
            $factura_compra=$id_tipo==2;
            $factura_venta=$id_tipo==3;
            $sTable = "products, comprobante, historial";
           $sWhere = "WHERE products.id_tipo=comprobante.id_tipo and products.id_producto=historial.id_producto"; 





           $suma_compras=0;
           $suma_ventas=0;
           $suma_utilidad=0;
           $suma_stock=0;
           $stock_compra=0;
           $stock_venta=0;
           $compra=0;
           $venta=0;
           $utilidad=0;

            $nums=1;
            while ($row=mysqli_fetch_array($query)) {
                    $codigo=$row['codigo'];

                    $numero_comprobante=$row['numero_comprobante'];
                    $descripcion=$row['descripcion'];
                    $precio=number_format($row['precio'],2,'.','');

                    $cantidad=$row['cantidad'];
                    $total=$row['total'];

                    $fecha= date('d/m/Y', strtotime($row['fecha']));
                    $id_tipo=$row['id_tipo'];
                    $id_categoria=$row['id_categoria'];
                    $id_proveedor=$row['id_proveedor'];


              $query_tipo=mysqli_query($con,"select * from tipo where id_tipo='".$id_tipo."'");


                         $fetch_tipo=mysqli_fetch_array($query_tipo);
                         $nombre=$fetch_tipo['nombre'];

                         $total=$precio*$cantidad; 
     $sql="INSERT INTO products (id_producto, codigo_producto, nombre_producto, date_added, precio_producto, stock, id_proveedor, id_categoria) VALUES ('$codigo', '$numero_comprobante','$descripcion','$fecha','$precio','$cantidad','$id_proveedor','$id_categoria')";
    $query_new_insert = mysqli_query($con,$sql);            
                        if ($nombre==$factura_compra){
                         $query_compra=mysqli_query($con,"select * from products where id_producto");                                                        
                         $fetch_compra=mysqli_fetch_array($query_compra);
                         $id_producto=$fetch_compra['id_producto'];
                         $id_categoria=$row['id_categoria'];
                         $id_proveedor=$row['id_proveedor'];
                         $query_stock=mysqli_query($con,"select * from products where stock");
                         $fetch_stock=mysqli_fetch_array($query_stock);
                         $stock=$fetch_stock['stock'];
                         $venta=0;  
                         $compra=$precio*$cantidad; 

                         $utilidad=$total-$utilidad;


                        }



                        elseif ($nombre==$factura_venta) {
                         $query_compra=mysqli_query($con,"select * from products where id_producto");                                                        
                         $fetch_compra=mysqli_fetch_array($query_compra);
                         $id_producto=$fetch_compra['id_producto'];

                         $query_stock=mysqli_query($con,"select * from products where stock");
                         $fetch_stock=mysqli_fetch_array($query_stock);
                         $stock=$fetch_stock['stock'];
                            $compra=0; 
                            $venta=$precio*$cantidad;

                            $utilidad=$total + $utilidad;                           
                        }
                        else {
                        $query_venta=mysqli_query($con,"select * from products where id_producto");                                                          
                         $fetch_venta=mysqli_fetch_array($query_venta);
                         $id_producto=$fetch_venta['id_producto'];

                         $query_stock=mysqli_query($con,"select * from products where stock");
                         $fetch_stock=mysqli_fetch_array($query_stock);
                         $stock=$fetch_stock['stock'];


                        $utilidad= $compra - $venta;                            


                        }



                    if ($id_tipo==2) {
                         $venta=0;  
                         $compra=$precio*$cantidad; 



                    }
                    elseif ($id_tipo==3) {
                        $compra=0; 
                            $venta=$precio*$cantidad;


                    } 

                    else {
                        $orden_pago = $cantidad-$cantidad;


                    }

                    $cantidades=$cantidad;
                    $stock=$cantidades;
                    $suma_stock+=$stock;
                    $utilidad=$venta - $compra;
                    $suma_compras+=$compra;
                    $suma_ventas+=$venta;
                    $suma_utilidad+=$utilidad;

                ?>
                <tr>



                    <td ><?php echo $numero_comprobante; ?></td>
                    <td ><?php echo $descripcion; ?></td>
                    <td >$ <?php echo $precio; ?></td>


                    <td ><?php echo $cantidad; ?></td>
                    <td >$ <?php echo number_format($total,2);?></td>

                    <td><?php echo $fecha?></td>
                    <td><?php echo $nombre; ?></td>
                    <td><?php echo $stock; ?></td>
                    <td><?php echo number_format ($compra,2); ?></td>
                    <td><?php echo number_format ($venta,2); ?></td>
                    <td><?php echo number_format ($utilidad,2); ?></td>




}                

Thanks. '

    
asked by adriancasanova 25.05.2018 в 14:22
source

3 answers

1

If you want to add a value to a variable you can use the expression + = o - =.

$ amounts + = $ amount is the same as $ quantities = $ quantities + $ amount

Notice that in your code "$ amounts = $ amount + $ amount;" You add twice the $ amount you receive and then assign that value to the variable $ quantities.

On the other hand you would need two different variables to store each description and then compare them. If you compare a variable with itself, it will always be the same.

You can try this code:

if ($descripcion1==$descripcion2) {
 switch($id_tipo) {
    case 1:
        $cantidades = $cantidad;
        break;
    case 2:
        $cantidades += $cantidad;
        break;
    case 3:
        $cantidades -= $cantidad;
        break;
    default:
        $cantidades = $cantidad;
        break;
 }
}
else {
 $cantidades= $cantidad;
}
    
answered by 25.05.2018 в 14:44
0

You can try storing the descriptions in a variable that is an array and then compare if the description exists in the array with the function in_array :

$descripciones = array("Hola", "Hola1", "Hola2", "Hola3");
if (in_array($descripcion, $descripciones)) {
    $cantidades += $cantidad;
}
    
answered by 25.05.2018 в 15:11
0

I already managed to solve it. I did it in the following way:

       ´$sql1= "select * from comprobante where 
        descripcion='".$descripcion."'";        
        $query1 = mysqli_query($con, $sql1);
        $fila = mysqli_num_rows($query1);     

        if ($fila==1) {
            $cantidades=$cantidad;

        }   
        else {
        if ($id_tipo==3) {
            $cantidades-=$cantidad;
        }           
        if ($id_tipo==2)  {

            $cantidades+=$cantidad;

        }

        if ($id_tipo==1)  {
            $cantidades-=$cantidad;             
        } 
        }´

I hope you can serve someone.

    
answered by 18.06.2018 в 14:58