0

I´m trying to make a function to calculate the price of a product. The function has two mysql queries inside it. If I run the code outside the function, it works well, but inside it doesn't.

So this works:

  $id = '1';
  $consultaC = "SELECT * FROM partes_insumos WHERE parte_id='$id'";
  $resultadoC = mysql_query($consultaC,$conexion);
  while($rArrayC = mysql_fetch_array($resultadoC)){
    $insumoId = $rArrayC['insumo_id'];
    $cantidad = $rArrayC['cantidad'];
    $consultaC2 = "SELECT * FROM insumos WHERE Id='$insumoId'";
    $resultadoC2 = mysql_query($consultaC2,$conexion);
    $rArrayC2 = mysql_fetch_array($resultadoC2);
    $precio = $rArrayC2['precio']*$cantidad;
    $total = $total+$precio;
  }
  echo $total;
  //echoes 107.1

But this doesn´t:

function precioParte($id) {
  $consultaC = "SELECT * FROM partes_insumos WHERE parte_id='$id'";
  $resultadoC = mysql_query($consultaC,$conexion);
  while($rArrayC = mysql_fetch_array($resultadoC)){
    $insumoId = $rArrayC['insumo_id'];
    $cantidad = $rArrayC['cantidad'];
    $consultaC2 = "SELECT * FROM insumos WHERE Id='$insumoId'";
    $resultadoC2 = mysql_query($consultaC2,$conexion);
    $rArrayC2 = mysql_fetch_array($resultadoC2);
    $precio = $rArrayC2['precio']*$cantidad;
    $total = $total+$precio;
  }
  echo $total;
}
precioParte('1');
//echoes nothing

I can´t find the problem and I need some help, thanks.

yom
  • 7
  • 4

1 Answers1

0

You can fix it like so:

  function precioParte($id) {
      global $conexion; // TRICK!
      $consultaC = "SELECT * FROM partes_insumos WHERE parte_id='$id'";
      $resultadoC = mysql_query($consultaC,$conexion);
      ...

Another solution is to inject $conexion into the function as an argument:

 function precioParte($conexion, $id) {
     ...
Jacobian
  • 10,122
  • 29
  • 128
  • 221
  • The problem is not with a loop, but with connection resource, which is not visible inside function, unless you make it visible explicitly. – Jacobian Mar 25 '18 at 20:19
  • parsing the variable in to the function is a better "trick" than using the (frowned upon) global `function precioParte($id,$conexion) {` –  Mar 25 '18 at 20:20
  • Yes, it is another solution. – Jacobian Mar 25 '18 at 20:21