sql >> Base de Datos >  >> RDS >> Mysql

php no pasa variables

El HTML tiene algunos errores y el formulario utilizado para buscar campings en realidad no envía ninguno de los datos, muy probablemente debido a algunos de los errores en el HTML. Un ul elemento puede tener li elementos solo como elementos secundarios, pero esos li los elementos pueden tener otro contenido (por lo general, no es la mejor manera de hacerlo, en mi opinión, en este caso) y los elementos de entrada de formulario de cualquier tipo deben tener un atributo de nombre y, en general, un valor. En el caso del formulario de reserva fire ,electric y sewer debe nombrarse como tal con un valor de 1 (consulte la pregunta anterior). Los selectores de fecha deben tener nombres, así que en lugar de una ID o también, asígneles el nombre startdate y enddate ya que el script php los espera en la matriz POST.

Si el formulario envió correctamente los datos y la consulta sql se ejecutó correctamente, ¿dónde aparecerían los resultados? Puedo ver que la acción del formulario es includes/reserve.inc.php que es la segunda parte del código ( PHP ) pero que no genera ningún contenido.

Editar el HTML en el navegador para agregar atributos a los diversos elementos del formulario y cambiar sus valores antes de enviar el formulario produjo los siguientes parámetros POST en la página activa...

startdate=01%2F03%2F2018&enddate=01%2F17%2F2018&fire=1&electric=1&sewer=1&submit1=

Mientras que antes solo el submit1 estaba apareciendo Sin embargo, aún no se devolvió ningún resultado.

Como ya tienes jQuery en la página para varias tareas, ¿quizás lo que hay que hacer sería usar ajax para PUBLICAR los datos en el script PHP backend y usar la devolución de llamada para agregar el contenido HTML a la página actual? Ciertamente, algo en lo que pensar tal vez.

<?php
    @session_start();
    require_once("includes/dbh.inc.php");
?>

<!DOCTYPE html>
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script>

            $(document).ready(function(){
              $('#login-trigger').click(function(){
                $(this).next('#login-content').slideToggle();
                $(this).toggleClass('active');

                if ($(this).hasClass('active')) $(this).find('span').html('&#x25B2;')
                  else $(this).find('span').html('&#x25BC;')
                })
            });

            $(document).ready(function(){
              $('#reserve-trigger').click(function(){
                $(this).next('#reserve-content').slideToggle();
                $(this).toggleClass('active');
                })
            });

            $('#reserve-trigger').on('focusout', function () {
              $(this).toggleClass('active');
            });

            $('#login-trigger').on('focusout', function () {
              $(this).toggleClass('active');
            });
        </script>
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js">
        <script>
            $(document).ready(function() {  $("#startdate").datepicker();  });
            $(document).ready(function() {  $("#enddate").datepicker();  });
        </script>
        <link rel="stylesheet" href="./css/style.css">
    </head>
    <body>
        <header>
            <div class='container'>
                <div id='branding'>
                    <h1><span class='highlight'>Whispering</span> Winds Park</h1>
                </div>
                <nav>
                    <ul>
                        <li class='current'><a href='index.php'>Home</a></li>
                        <li><a href='mission.php'>Our Mission</a></li>
                        <li><a href='donate.php'>Donate</a></li>
                        <li><a id='reserve-trigger' href='#'>Camping</a>
                            <div id='reserve-content' tabindex='-1'>

                                <form action='includes/reserve.inc.php' method='POST'>
                                    <fieldset>
                                        <!--

                                            child elements of a `ul` should be `li` only
                                            so you required a few more `<li></li>` around
                                            certain items here

                                            Form input elements require a name attribute and a type for the datepickers

                                        -->
                                        <ul>
                                            <li><input type='text' id='startdate' name='startdate' placeholder='Start Date' /></li>
                                            <li><input type='text' id='enddate' name='enddate' placeholder='End Date'/></li>
                                            <!--

                                                The checkboxes require a name attribute otherwise they will not appear
                                                in the POST array data. Set the value to `1` as it is a bit stored in 
                                                the db anyway

                                            -->
                                            <li><label for='fire'>Fire Pit: </label><input type='checkbox' name='Fire' value=1></li>
                                            <li><label for='electric'>Electricity: </label><input type='checkbox' name='Electric' value=1></li>
                                            <li><label for='sewer'>Sewage: </label><input type='checkbox' name='Sewer' value=1></li>
                                            <li><button type='submit' class='button3' name='submit1'>Find a Reservation</button></li>
                                        </ul>
                                    </fieldset>
                                </form>

                            </div>
                        </li>

                        <!-- /*login button*/ -->
                        <?php
                            if( isset( $_SESSION["u_uid"] ) ) {
                                echo '
                                <li>
                                    <form action="includes/logout.inc.php" method="POST">
                                        <button type="submit" class="button_1" name="Submit">Logout</button>
                                    </form>
                                </li>';

                            } else {

                                echo
                                '<li id="login">
                                    <a id="login-trigger" href="#">
                                        <button class="button_1">Log in <span>▼</span></button>
                                    </a>
                                    <div id="login-content" tabindex="-1">
                                        <form action="includes/login.inc.php" method="POST">
                                            <fieldset id="inputs">
                                                <input type="text" name="uid" placeholder="Username" required>
                                                <input type="password" name="pwd" placeholder="Password" required>
                                                <button type="submit" class="button3" name="Submit">Log In</button>
                                            </fieldset>
                                        </form>
                                    </div>
                                </li>
                                <li id="signup">
                                    <a href="signup.php"><button class="button_1">Sign up</button></a>
                                </li>';
                            }
                            if( isset( $_SESSION["u_admin"] ) ) {
                                echo '
                                <li id="signup">
                                  <a href="admin.php"><button class="button_1">Admin</button></a>
                                </li>';
                            }
                        ?>
                  </ul>
                </nav>
            </div>
        </header>
    </body>
</html>

Pasando al script de back-end.

¿Tiene mesas llamadas campsite? y campsites ? Todas las declaraciones SQL tienen variables incrustadas que, a pesar del uso de mysqli_real_escape_string , deja su código potencialmente vulnerable a la inyección de SQL, por lo que debe usar prepared statements siempre que esté utilizando la entrada proporcionada por el usuario. ¡Solo se necesita un campo que pueda explotarse para comprometer todo el sistema! No pude seguir algo de la lógica con lo que estaba sucediendo allí (probablemente todavía no hay suficiente cafeína), por lo que lo siguiente puede estar fuera de lugar

<?php
    session_start();

    /* Prevent direct access to this script in the browser */
    if ( realpath(__FILE__) == realpath( $_SERVER['SCRIPT_FILENAME'] ) ) {

        /* could send a 403 but Not Found is probably better */
        header( 'HTTP/1.0 404 Not Found', TRUE, 404 );
        die( header( 'location: /index.php' ) );
    }

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submit1'], $_POST['startdate'], $_POST['enddate'], $_POST['fire'], $_POST['electric'], $_POST['sewer'] ) ) {

        if ( empty( $_POST['startdate'] ) || empty( $_POST['enddate'] ) ) {
            exit( header( 'Location: ../index.php?index=empty_dates' ) );
        }


        /* results from search query will be stored in this array for later use */
        $output=array();

        require_once('dbh.inc.php');

        /*
            Do startdate and enddate need to be session variables???
        */
        $startdate = filter_input( INPUT_POST,'startdate',FILTER_SANITIZE_SPECIAL_CHARS );
        $enddate = filter_input( INPUT_POST,'enddate',FILTER_SANITIZE_SPECIAL_CHARS );
        $fire = filter_var( filter_input( INPUT_POST,'fire', FILTER_SANITIZE_NUMBER_INT ), FILTER_VALIDATE_INT );
        $electric = filter_var( filter_input( INPUT_POST,'electric', FILTER_SANITIZE_NUMBER_INT ), FILTER_VALIDATE_INT );
        $sewer = filter_var( filter_input( INPUT_POST,'sewer', FILTER_SANITIZE_NUMBER_INT ), FILTER_VALIDATE_INT );

        /*
            Dates from the DatePicker are in mm/dd/yyyy
            but typically we would want to use yyyy/mm/dd
            in the database.
        */
        $startdate=DateTime::createFromFormat( 'm/d/Y', $startdate )->format('Y-m-d');
        $enddate=DateTime::createFromFormat( 'm/d/Y', $enddate )->format('Y-m-d');



        if( $fire > 1 or $fire < 0 or is_string( $fire ) ) $fire=0;
        if( $electric > 1 or $electric < 0 or is_string( $electric ) ) $electric=0;
        if( $sewer > 1 or $sewer < 0 or is_string( $sewer ) ) $sewer=0;


        $sql='select `site_id`,`uid`,`startdate`,`enddate`,`s_price` from `campsite` 
                where `water`=? and `fire`=? and `electric`=? and `site_id` not in ( 
                    select `site_id` 
                    from `reservation` 
                    where `startdate` >= ? and `startdate` <= ?
                )';

        $stmt=$conn->prepare( $sql );
        if( $stmt ){

            $stmt->bind_param('iiiss', $sewer, $fire, $electric, $startdate, $enddate );
            $result = $stmt->execute();
            $rows = $result->num_rows;

            if( $result && $rows > 0 ){

                $stmt->store_result();
                $stmt->bind_result( $id, $uid, $start, $end, $price );

                while( $stmt->fetch() ){
                    $output[]=array(
                        'site_id'   =>  $id,
                        'uid'       =>  $uid,
                        'startdate' =>  $start,
                        'enddate'   =>  $end,
                        's_price'   =>  $price
                    );
                }
                $stmt->free_result();
                $stmt->close();
                $conn->close();

                /* 
                    Now we should have an array with the recordset data from the search
                    Depending upon form submission method ( standard or ajax ) you need to
                    do something with that data. Typically you would let the user know the
                    results of the search ( otherwise what is the point of letting them search? )

                    So, you could format the results here as HTML or send back json etc
                */
                foreach( $output as $index => $site ){
                    echo "
                    <pre>
                        {$site['site_id']}
                        {$site['uid']}
                        {$site['startdate']}
                        {$site['enddate']}
                        {$site['s_price']}
                    </pre>";
                }

            } else {
                exit( header('Location: /index.php?error=no_available_camps') );
            }
        } else {
            echo "Failed to prepare sql query";
        }
    }
?>
"; } } else { exit( header('Ubicación:/index.php?error=no_disponible_camps') ); } } else { echo "Error al preparar la consulta sql"; } }?>

Había otras declaraciones de sql allí, pero como dije, no podía seguir la lógica, por lo que lo anterior probablemente esté incompleto/erróneo, pero debería ayudar un poco con las declaraciones preparadas al menos.

Otros puntos

Tiene un error no controlado en campground.php página que revela

includes/reserve.php y /reserve.php ambos arrojan un 404-Not Found error

Quizás use un .htaccess archivo dentro de las images directorio para evitar la vinculación directa o la exploración de directorios.

Hay algunas imágenes asombrosas allí, pero algunas son, para ser honesto, absolutamente enormes y, a pesar de que la mayoría de las personas tienen una banda ancha rápida, la descarga de un jpg de 3,7 Mb como parte del flujo HTML ralentiza un poco las cosas, por lo que tal vez alguna optimización de imagen sería una buena idea también Dicho esto, ¡me encantaría ir a este lugar yo mismo!