While loop inside function not working

时间:2018-03-25 20:14:46

标签: php mysql

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.

1 个答案:

答案 0 :(得分: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) {
     ...