sql problems for booking inquiries

0

I am creating a small web booking application for boats, where the client can check which ones are available and, based on this information, reserve one from the list.

My PHP query script is this (also here ):

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);

include ("../base/conexion/conexion.php");


        $fecha_i = "2016-10-22";

        //$fecha_inicio = $_POST['fecha_inicio'];
        $fecha_inicio=   date('Y-m-d', strtotime($fecha_i) );
        //$inicio_f = str_replace('/', '-', $fecha_inicio);
        //$inicio = date('Y-m-d', strtotime($inicio_f));


        $fecha_f = "2016-10-22";

        //$fecha_fin      = $_POST['fecha_fin'];
        $fecha_fin  =   date('Y-m-d', strtotime($fecha_f ) );
        //$fin_f = str_replace('/', '-', $fecha_fin);
        //$fin = date('Y-m-d', strtotime($fin_f));




//-------------------------Rango de Fechas -------------------------
function createDateRangeArray($strDateFrom,$strDateTo = null)
{
    // takes two dates formatted as YYYY-MM-DD and creates an
    // inclusive array of the dates between the from and to dates.
    $aryRange=array();

    $iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2),     substr($strDateFrom,8,2),substr($strDateFrom,0,4));
    $iDateTo=mktime(1,0,0,substr($strDateTo,5,2),     substr($strDateTo,8,2),substr($strDateTo,0,4));

    if ($iDateTo>=$iDateFrom)
    {
        array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
        while ($iDateFrom<$iDateTo)
        {
            $iDateFrom+=86400; // add 24 hours
            array_push($aryRange,date('Y-m-d',$iDateFrom));
        }
    }
    return $aryRange;
}


    //Array de fechas presentes entre los rangos
    $array_rango_fechas = createDateRangeArray($fecha_inicio,$fecha_fin);
        //print_r($array_rango_fechas);

    //guardamos en una cadena de strings las fechas de dias reservados
    $fechas_a_reservar = implode(',' ,$array_rango_fechas );

    //print "Dias a reservar : ".$fechas_a_reservar."\n";


//------------------------------------------------


        //--Comprobar reservas--
        //reservas hechas entre los días elegidos - descartar de lista de barcos a mostrar


        $comprobar_reservas = mysqli_query($con," SELECT flotaid FROM disponibilidad WHERE DESDE >  $fecha_inicio 
            AND HASTA >  $fecha_fin" );
            //$comprobar_reservas_fin = mysql_query(" SELECT RESERVA FROM disponibilidad 
                //WHERE HASTA <= '2016-11-11'" );


            /*$comprobar_reservas = mysqli_query($con,"SELECT flotaid FROM reservas_prueba
                WHERE DESDE NOT IN ($fechas_a_reservar)

                union 

                SELECT flotaid FROM disponibilidad 
                WHERE HASTA IN ($fechas_a_reservar) ");*/

            $row = mysqli_fetch_array($comprobar_reservas );

            print_r($row);

            /*$comprobar_reservas = mysql_query("SELECT flotaid  FROM disponibilidad 
                WHERE DESDE IN  ('$fechas_a_reservar') AND HASTA IN ('$fechas_a_reservar')" );*/

        //print_r($comprobar_reservas);
        //-->las querys devuelven la reserva del barco de ID = 4,
        //asi que se listan los barcos que no tengan esa ID

        //$row = mysql_fetch_array($comprobar_reservas);


        $num_rows = mysqli_num_rows($comprobar_reservas);

    if($num_rows > 0){
        //ARRAY que guardará los IDs/Nombres de barcos ya reservados,
        //y de esta forma sabremos cuáles estan disponibles descartando
        $barcos_no_disponibles = array();




        $i = 0;

            while($row = mysqli_fetch_assoc($comprobar_reservas))
            {
               $lista_barcos_no_disponibles = $row;

            }


            $barcos_no_disponibles = implode(',' , $lista_barcos_no_disponibles );
            /*
            $barcos_no_disponibles_b = implode(',' ,$barcos_no_disponibles_b );
            $barcos_no_disponibles = $barcos_no_disponibles_a.$barcos_no_disponibles_b;*/

            //array_push();





        //print_r("Ids Barcos no disponibles : ".$barcos_no_disponibles."\n");


        //---COMPROBAR flota con ID (?)
            $comprobar_flota = mysqli_query($con,"SELECT * FROM flota WHERE FLOTAID NOT 
                IN ('$barcos_no_disponibles') ");

            $array_flota = array();
            $i = 0;


            while($row = mysqli_fetch_array($comprobar_flota)) {

                $array_flota[$i]['FLOTAID']         = $row['FLOTAID'];
                $array_flota[$i]['NOMBRE']          = utf8_encode($row['NOMBRE']);
                $array_flota[$i]['CARACTERISTICAS'] = utf8_encode($row['CARACTERISTICAS']);
                $array_flota[$i]['EQUIPAMIENTO']    = utf8_encode($row['EQUIPAMIENTO']);

                $i++;
            }

            //print_r($array_flota);


            header("Content-Type: application/json; charset=utf-8;");
            $json =  json_encode($array_flota,JSON_HEX_QUOT);
            if(empty($json)){
                die("no funciona");
            }else{
                echo json_encode($array_flota);
            }
            exit;

    }else{
        header("Content-Type: application/json");
        echo json_encode(array());
        exit;
    }   

?>

Steps to book:

  • The client specifies the dates on which he wants to have the boat booked, using fields input of which a calendar is displayed.

  • The information is sent through AJAX to a script that makes the query. A chain with dates within the range between Start date and End date is created.
    The existing reserves that have dates within that range will not be shown, the others will.

  • The user obtains a list of available boats. Specify your data and send the reservation to the web.

  • I am sure that my reservation checking query is not as correct as it should be, since it does not return the dates I want . Sometimes it goes wrong, sometimes just the last.

        
    asked by Víc M.R. 13.10.2016 в 12:52
    source

    5 answers

    2
    SELECT flotaid 
    FROM disponibilidad 
    WHERE ($fecha_inicio BETWEEN DESDE AND HASTA) AND ($fecha_fin BETWEEN DESDE AND HASTA)
    

    In the query valid both dates: the start and end, since what should be validated the given date interval and not a single date.

        
    answered by 13.10.2016 в 13:41
    0

    If you are looking for availability between a range of dates what you can try is this way:

    SELECT flotaid FROM disponibilidad WHERE DESDE > $fecha_inicio AND HASTA < $fecha_fin"

        
    answered by 13.10.2016 в 13:17
    0

    Assuming that the fields DESDE and HASTA have data type "date", so that the comparison is done correctly, the simplest way would be:

    SELECT flotaid FROM disponibilidad WHERE DESDE >= '$fecha_inicio' AND HASTA <= '$fecha_fin'
    
    • $fecha_inicio and $fecha_fin with format "aaaa-mm-dd" ;
    answered by 13.10.2016 в 14:46
    0

    only as an additional comment

    the date variables in the query string should be in quotes

    "SELECT flotaid FROM disponibilidad WHERE DESDE >  '$fecha_inicio' AND HASTA < '$fecha_fin'"
    
        
    answered by 13.10.2016 в 15:14
    0

    Thank you very much everyone for your answers, but I can only list the last ship of the results, that is, if you return IDs 1,2 and 3, it only returns num 3. Let's see what's wrong.

        
    answered by 17.10.2016 в 11:16