0

I'm trying to understand the best way to use a function's arguments in nested functions:

Here are my thoughts:

These are a bunch of functions I first declare to use them later in other functions:

//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;
        }

So here is the main function:

//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;
                }
        }
}

So here is my doubt, the argument: $room_type_id is the only one which I need to change in the main function to get what I want from every room in the database, and each function should be used with that variable as parameter to change such information... my question is, if I define the room type id once in the main variable, will this be also accepted and used for all the others functions as a value for this argument? lets say:

function next("7");

Will the number 7 be used for all the other nested functions inside this function as a value for the same argument?

Thanks in advance for your help.

2
  • 1
    Your code is likely vulnerable to SQL injection attacks. You should use prepared statements with bound parameters, via either the mysqli or [PDO](secure.php.net/manual/en/pdo.prep ared-statements.php) drivers. This post has some good examp les. Commented Aug 31, 2017 at 15:45
  • Thanks Alex, i'm still trying to learn, i'll read the documentation and examples and see if i understand it... thanks for pointing that Commented Aug 31, 2017 at 15:57

1 Answer 1

1

Will the number 7 be used for all the other nested functions inside this function as a value for the same argument?

The answer is 'yes'.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Jay, i had a couple of errors while trying to make it work, because of some arguments which i forgot to define, but once checked again it worked as your concrete answer said... In other words, Functions arguments are passed through nested functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.