2

what is the best way to direct the user to another page given the IF statement is true. i want the page to direct the user to another page using PHP, when the IF statement is run, i tired this but it doesn't work??

    if ( mysqli_num_rows ( $result ) > 0 )
    {

    header('Location: exist.php'); 
    die();

    }

Below is the full source code for the page.

<?php

    // starts a session and checks if the user is logged in
    error_reporting(E_ALL & ~E_NOTICE);
    session_start();

    if (isset($_SESSION['id'])) {
        $userId = $_SESSION['id'];
        $username = $_SESSION['username'];


    } else {
        header('Location: index.php');
        die();

    }   

?>



<!DOCTYPE html>

<html lang="en">



    <head>

    </head>



    <body>

        <p><span>Room No: </span><?php $room = $_SESSION['g'];

                echo $room; // echo's room ?>
        </p>



        <p><span>Computer No: </span><?php 

                $select3 = $_POST['bike'];
                echo  $select3;
                ?>
        </p>



        <p><span>Date: </span><?php $date = $_POST['datepicker']; 
                echo $date; // echo's date 
                ?> 
        </p>



        <p><span>Start Session: </span>
                <?php   
                if(isset($_POST['select1'])) {
                $select1 = $_POST['select1'];
                echo $select1;
                echo "";
                }
                else{
                echo "not set";
                }
                ?>
        </p>

        <p><span>End Session: </span>
                <?php   
                if(isset($_POST['select2'])) {
                $select2 = $_POST['select2'];
                echo $select2;
                echo "";
                }
                else{
                echo "not set";
                }
                ?>
        </p>


        </div>




        <div id="success">

 <?php

            $servername = "localhost";
            $name = "root";
            $password = "root";
            $dbname = "my computer";

            // Create connection
            $conn = mysqli_connect($servername, $name, $password, $dbname);
            // Check connection
            if (!$conn) {
               die("Connection failed: " . mysqli_connect_error());
            }



$query = "SELECT * FROM `booked` WHERE 
        `date` = '{$date}' AND 
        `computer_id` = '{$select3}' AND 
        `start_time` = '{$select1}' AND 
        `end_time` = '{$select2}' AND 
        `room` = '{$room}'
        ";

            $result = mysqli_query($conn, $query);



            if ( mysqli_num_rows ( $result ) > 0 )
            {

            header('Location: exist.php'); 
            die();

            }




            else
            {
            $sql = "INSERT INTO booked (date, computer_id, name, start_time, end_time, room)
                VALUES ('$date', '$select3', '$username', '$select1', '$select2', '$room')";



            if (mysqli_query($conn, $sql)) {
               echo "New record created successfully";
                } else {
               echo "Error: " . $sql . "<br>" . mysqli_error($conn);
                }

            mysqli_close($conn);

            }
            ?>

        </div>



        <form action="user.php">
            <input type="submit" value="book another" class="bookanother" />
        </form>



        </div>


    </body>




</html>
kate tango
  • 23
  • 5
  • The reason it does not work is because the `header()` function must be called before any output is sent to the browser. http://php.net/manual/en/function.header.php – Jacob Mulquin Jul 07 '16 at 04:46
  • try moving the header as the first line and see if it working, else follow my answer and try a javascript fallback. usually header location issue happens if you already send the header. – Iceman Jul 07 '16 at 04:47
  • Possible duplicate of [How to fix "Headers already sent" error in PHP](http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) – Qirel Jul 07 '16 at 04:48

1 Answers1

2

If the header is sent already, for example you have echo something before then the header will not work, because the header cannot be set after data flow has started, (since php would have already set the default headers for you). So, in this case if that is so, I do the redirect using javascript.

PHP Docs:

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

WORK-AROUND: This is a function I have written long back and include in controllers.

     /**
     * Safely redirect by first trying header method but if headers were
     * already sent then use a <script> javascript method to redirect
     *
     * @param string
     * @return null
     */
    public function safeRedirect($new_url) {
        if (!headers_sent()) {
            header("Location: $new_url");
        } else {
            echo "<script>window.location.href = '$new_url';</script>";
        }
        exit();
    }

add the function and simply call:

safeRedirect('index.php');
Iceman
  • 6,035
  • 2
  • 23
  • 34