2017-08-31 188 views
0

我试图了解使用函数的参数中嵌套函数的最佳方式:如何使用函数的参数PHP

这里是我的想法:

这是一组函数我首先声明使用他们后来在其他功能:

//Habitaciones restantes 
     function rleft($from, $to, $room_type_id){ 
      //Acceso a DB 
       require('/some-path/database.php'); 
      //url parameters 
       require ('/some-path/getparam.php'); 
      //Hotel Room Data 
       $customroom = mysqli_query($conn, "SELECT * FROM hotel_room_type WHERE room_type_id = '$room_type_id'"); 
       $customroomtotal = mysqli_num_rows($customroom); 
       $customroomData = mysqli_fetch_array($customroom); 
       $roominventory = $customroomData['room_type_inventory']; 
      //Obteniendo lista de disponibilidad 
       $customavailable = mysqli_query($conn, "SELECT * FROM booking_check_avilability WHERE room_type_id = '1' AND check_in_date = '$from' AND check_out_date = '$to'"); 
       $customavailabletotal = mysqli_num_rows($customavailable); 
       mysqli_close($conn); 
       if($customavailabletotal > 0) { 
        while($customavailableData = mysqli_fetch_array($customavailable)) {   
          $inventariodisponible = $roominventory - $customavailableData['total_room'] -$customavailableData['blocked_inventory']; 
        } 
       } mysqli_free_result($customavailable); 
       mysqli_close(conn); 
      return $inventariodisponible; 
     } 
    //Creamos el array donde se almacenarán todos los dias entre las 2 fechas del cliente 
     function createRange($startDate, $endDate) { 
       $tmpDate = new DateTime($startDate); 
       $tmpEndDate = new DateTime($endDate); 
       $outArray = array(); 
       do { 
        $outArray[] = $tmpDate->format('Y-m-d'); 
       } while ($tmpDate->modify('+1 day') < $tmpEndDate); 
      return $outArray; 
     } 
    //creamos un array donde se almacenará la dispo para cada una de las fechas del cliente 
     function inout($room_type_id){ 
     require ('/some-path/getparam.php'); 
      $datearray = createRange("$fromdate", "$todate", "$room_type_id"); 
      $arraycount = count($datearray); 
      $leftarray = array(); 
      foreach ($datearray as $value) { 
       $from = $value; 
       $to = date('Y-m-d',strtotime($value . "+1 days")); 
       $leftarray[] = rleft($from, $to); 
      } 
      return $leftarray; 
     } 
    //Room or Rooms? 
     function sp(){ 
     require ('/some-path/getparam.php'); 
      if (rleft($fromdate, $todate, $room_type_id) == 1) { 
       $rq = "room"; 
      } 
      else{ 
       $rq = "rooms"; 
     } 
     return $rq; 
     } 
    //Habitaciones restantes 
     function availablerooms(){ 
      //Acceso a DB 
      require('/some-path/database.php'); 
      //url parameters 
      require ('/some-path/getparam.php'); 
      $keyarray = createrange($fromdate, $todate); 
      $valuearray = inout(); 
      $joinarray = array(); 
      foreach ($keyarray as $i => $key) { 
       $joinarray[$key] = $valuearray[$i]; 
      } 
      return $joinarray; 
     } 

因此,这里的主要功能是:

//Función para checkar si hay disponibilidad para las fechas seleccionadas 
    function next($room_type_id){ 
     //basic include files 
      require('/some-path/database.php'); 
     //url parameters 
      require ('/some-path/getparam.php'); 
     //Checkamos que haya dispo 
     $inoutarray = inout("$room_type_id"); 
     foreach ($inoutarray as $value) { 
      if ($value < $rooms) { 
       echo "Sorry NO rooms available!"; //no hay habitaciones disponibles 
        echo "</br>"; 
         ?> 
         <!-- Escondemos el botón de submit de la habitación --> 
         <style type="text/css">.bromeliabtn{ 
         display:none!important; 
         }</style> 
         <!-- Cambiamos el estilo del msj --> 
         <style type="text/css">.bromeliadsbl span{ 
         color: #c58e21!important; 
         font-size: 20px!important; 
         line-height: 25px!important; 
         }</style> 
         <?php 
         $cond = true;//asignamos un valor a $cond 
          break; // si match entonces termina el loop 
      }else{ 
      unset($cond); 
      $cond = false;//si hay disponibilidad entonces sumar 1 a $cond 
      } 
     } 
     //si las fechas tienen dispo entonces seguimos :) 
     if ($cond == false) {//si $cond es 2 entonces podemos seguir 
      allowed(); 
     } 

    } 
     //Esta función nos permite obtener los precios tanto de temporada como normales de acuerdo a la fecha especificada. 
      function allowed($room_type_id){ 
      //Acceso a la base de datos 
       require('/some-path/database.php'); 
       require ('/some-path/getparam.php'); 
        //Creamos la consulta para precios por temporada 
      $sql = "SELECT `seasonal_price`" 
       . " FROM `hotel_seasonal_price`" 
       . " WHERE `room_type_id` = '$room_type_id'" 
       . " AND `room_person` = '$Room1'" 
       . " AND `seasonal_price_deleted` = '0'" 
       . " AND '" . $fromdate . "' = seasonal_from" 
       //. " AND '" . $currentdate . "' = 'seasonal_to'" 
       . " LIMIT 1"; 
      $result = mysqli_query($conn, $sql) or die(mysqli_error()); 
      if (mysqli_num_rows($result) != 0) { 
       $seasonalprice = mysqli_query($conn, $sql); 
       if (!$seasonalprice) { 
        die('Could not get data: ' . mysqli_error()); 
       } else { 
        while ($standard2 = mysqli_fetch_assoc($seasonalprice)) { 
         //echo "$ " . $standard2['seasonal_price'] . ""; 
         $stdrd = $standard2['seasonal_price']; 
         echo "$ "; 
         echo number_format((float)($stdrd + ((10*$stdrd)/100)), 2, '.', ''); //sumamos el porcentaje de descuento que luego sera restado en el precio principal 
         echo " "; 
         ?> 
         <p style="text-align: center;"><span style="font-family: helvetica; color: #ff0000; font-size: 15px;"><span style="color: #333333;">(Seasonal price)</span></span></p> 
         <?php 
        } 
       } 
      } 
      else { 
      // Hacemos la consulta para obtener el precio sin importar fechas... solo como referencia 
       $weekend = date('l', strtotime($datefrom)); 
       switch ($weekend) { 
        case "Friday": 
         $sql = "SELECT `room_price_fri` FROM `hotel_room_price` WHERE room_type_id = '$room_type_id' AND `room_person` = '$Room1' AND `price_deleted` = '0'"; 
          $standardprice = mysqli_query($conn, $sql); 
          if (!$standardprice) { 
           die('Could not get data: ' . mysqli_error()); 
          //movemos el "while" dentro del "else" 
          } 
          else { 
           while ($standard = mysqli_fetch_array($standardprice, MYSQLI_ASSOC)) { 
            $stdrd2 = $standard['room_price_fri']; 
            echo "$ "; 
            echo number_format((float)$stdrd2, 2, '.', ''); 
            ?> 
            <p style="text-align: center;"><span style="font-family: helvetica; color: #ff4c00; font-size: 12px;"><span style="color: rgba(255, 76, 0, 0.63);"><?php echo "10% OFF"; ?></span></span></p> 
            <?php 
           } 
           mysqli_close($conn); //cerramos la conexión con la base de datos 
          } 
         break; 
        case "Saturday": 
         $sql = "SELECT `room_price_sat` FROM `hotel_room_price` WHERE room_type_id = '$room_type_id' AND `room_person` = '$Room1' AND `price_deleted` = '0'"; 
          $standardprice = mysqli_query($conn, $sql); 
          if (!$standardprice) { 
           die('Could not get data: ' . mysqli_error()); 
          //movemos el "while" dentro del "else" 
          } 
          else { 
           while ($standard = mysqli_fetch_array($standardprice, MYSQLI_ASSOC)) { 
            $stdrd2 = $standard['room_price_sat']; 
            echo "$ "; 
            echo number_format((float)$stdrd2, 2, '.', ''); 
            ?> 
            <p style="text-align: center;"><span style="font-family: helvetica; color: #ff4c00; font-size: 12px;"><span style="color: rgba(255, 76, 0, 0.63);"><?php echo "10% OFF"; ?></span></span></p> 
            <?php 
           } 
           mysqli_close($conn); //cerramos la conexión con la base de datos 
          } 
         break; 
        case "Sunday": 
         $sql = "SELECT `room_price_sun` FROM `hotel_room_price` WHERE room_type_id = '$room_type_id' AND `room_person` = '$Room1' AND `price_deleted` = '0'"; 
          $standardprice = mysqli_query($conn, $sql); 
          if (!$standardprice) { 
           die('Could not get data: ' . mysqli_error()); 
          //movemos el "while" dentro del "else" 
          } 
          else { 
           while ($standard = mysqli_fetch_array($standardprice, MYSQLI_ASSOC)) { 
            $stdrd2 = $standard['room_price_sun']; 
            echo "$ "; 
            echo number_format((float)$stdrd2, 2, '.', ''); 
            ?> 
            <p style="text-align: center;"><span style="font-family: helvetica; color: #ff4c00; font-size: 12px;"><span style="color: rgba(255, 76, 0, 0.63);"><?php echo "10% OFF"; ?></span></span></p> 
            <?php 
           } 
           mysqli_close($conn); //cerramos la conexión con la base de datos 
          } 
         break; 
        default: 
         $sql = "SELECT `room_price` FROM `hotel_room_price` WHERE room_type_id = '$room_type_id' AND `room_person` = '$Room1' AND `price_deleted` = '0'"; 
          $standardprice = mysqli_query($conn, $sql); 
          if (!$standardprice) { 
           die('Could not get data: ' . mysqli_error()); 
          //movemos el "while" dentro del "else" 
          } 
          else { 
           while ($standard = mysqli_fetch_array($standardprice, MYSQLI_ASSOC)) { 
            $stdrd2 = $standard['room_price']; 
            echo "$ "; 
            echo number_format((float)$stdrd2, 2, '.', ''); 
            ?> 
            <p style="text-align: center;"><span style="font-family: helvetica; color: #ff4c00; font-size: 12px;"><span style="color: rgba(255, 76, 0, 0.63);"><?php echo "10% OFF"; ?></span></span></p> 
            <?php 
           } 
           mysqli_close($conn); //cerramos la conexión con la base de datos 
          } 
         break; 
       } 
     } 
} 

所以这里是我的疑问,参数:$room_type_id是唯一需要在主函数中更改以获取我想要从数据库中的每个房间获得的内容,并且每个函数都应该与该变量一起用作参数来更改此类参数信息......我的问题是,如果我在主变量中定义了一次房间类型ID,是否也会将其作为此参数的值接受并用于所有其他函数?可以说:

function next(“7”);

将数字7用于该函数内的所有其他嵌套函数作为相同参数的值吗?

在此先感谢您的帮助。

+0

您的代码可能容易受到[** SQL注入**](https://en.wikipedia.org/wiki/SQL_injection)攻击。您应该通过[** mysqli **](https://secure.php.net/manual/en/mysqli.prepare.php)或[** PDO **](参数)绑定 参数https://secure.php.net/manual/en/pdo.prep ared-statements.php)驱动程序。 [**这篇文章**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)有一些很好的例子 les。 –

+0

感谢亚历克斯,我仍然在努力学习,我会阅读文档和示例,看看我是否理解它......谢谢指出, – GTCR

回答

3

将数字7用于该函数内的所有其他嵌套函数作为相同参数的值吗?

答案是'是'。

+0

感谢杰伊,我有一些错误,同时试图使其工作,因为我忘了定义一些参数,但一旦再次检查它的工作作为你的具体答案说... 换句话说,函数参数通过嵌套函数传递。 – GTCR