Lamia
Lamia

Reputation: 49

PHP return to same page with call to header() function

Hi I'm making a php page that return to itself when submitting form, but there's a case inside the php that when it's true a header("Location: url") function should be performed.

Is it possible to do so?

        <form action="" method="post">
      <input type="text" name="username" value="" />
        <?php
 if (isset($_POST['submitted'])) {

$username = $_POST['username'];

        $qryS="SELECT * FROM student WHERE ID='$username';";
        $resultS=mysql_query($qryS);
            if($resultS){
            if(mysql_num_rows($resultS)>=1) {

            header("location: studentprofile.php");
            }}
                else {

            echo"<p><small> There was an error</p>";

            }   
}

         ?>
      <input type="submit" name="submitted" value="Submit" /></p>

    </form>

Upvotes: 0

Views: 3291

Answers (5)

denisko
denisko

Reputation: 94

You can use JavaScript.

For example:

<?php
...
if(mysql_num_rows($resultS)>=1) {
    ?>
    <script>
    window.location = 'studentprofile.php';
    </script>
    <?php
}}

Upvotes: -1

Mehdi Yeganeh
Mehdi Yeganeh

Reputation: 2129

You should use header("location: studentprofile.php"); before anything. Use it at the top of your file, before the html tags.

Upvotes: 0

Brian Kerr
Brian Kerr

Reputation: 401

<?php
if (isset($_POST['submitted'])) {

    $username = mysql_real_escape_string($_POST['username']);

    $qryS = "SELECT * FROM student WHERE ID='$username'";
    $resultS = mysql_query($qryS);

    // changed to == 1, you probably only want to select one record
    if(mysql_num_rows($resultS) ==1) {
        header("location: studentprofile.php");
    } else {
        echo"<p><small> There was an error</p>";
    }
}
?>

<form action="?submitted" method="post">
<input type="text" name="username" value="" />
<input type="submit" name="submitted" value="Submit" /></p>
</form>

Upvotes: 0

Clarence
Clarence

Reputation: 2964

You can not send any headers after you already sent data (HTML). If you move the if-clauses and header() calls to before you output anything - there's no problems.

Upvotes: 3

Michael
Michael

Reputation: 12806

Yes, it is possible (so long as no output is sent to the browser -- you can use output buffering in your case). You just have to ensure that the logic prevents a redirect loop.

Upvotes: 0

Related Questions