Sam
Sam

Reputation: 45

PHP page not redirecting after form submission?

I have a little page that is just supposed to make a table in mysql from post data and then redirect to "second_page.php" but for some reason, after the form submits, it doesnt redirect.

<?php
 $connection =mysqli_connect("localhost", "widget_cms", "password", "widget_corp");
?>
<html>
<body>
<form name="login" action="login.php">
Username: <input type="text" name="username"></br>
<input name="submit" type="submit" value="Submit" style="cursor:pointer">
</form>
<?php
      $username = $_POST['username'];
      $username = mysqli_real_escape_string($connection, $username);
      $query = "INSERT INTO subjects (menu_name) VALUES ('{$username}')";
      if(isset($_POST['submit'])){
          $qresult = mysqli_query($connection, $query);
          if($qresult){
               header("Location: second_page.php");
          }else{
               die("Error " . mysqli_error($connection) . " "
                   . "(" . mysqli_errno($connection) . ")" .", 
               Please contact Sammy for troubleshooting as soon as you can.");
          }
     }
?>
</body>
</html>
<?php 
      mysqli_close($connection);
?>

Also for some reason it doesnt make a table, not sure what im doing wrong there either.

Upvotes: 0

Views: 3501

Answers (6)

apokryfos
apokryfos

Reputation: 40673

You cannot have a redirect after you have written text in your output. You need to have it before. What will happen is, when your page loads, you first check if you're here because of user input (submit is set and there's a username) or if not (first time a user navigates to the page). Then you can choose to redirect accordingly.

Update: Made form use POST rather than the default.

<?php 
    $connection = mysqli_connect("localhost", "widget_cms", "password", "widget_corp"); 
    if (isset($_POST["username"])) {
        $username = $_POST['username'];        
        $query = "INSERT INTO subjects (menu_name) VALUES (?)"; //Use prepared statements instead of unsafe methods
        if (isset($_POST['submit'])) {
            $stmt = mysqli_prepare($connection, $query);
            $stmt->bind_param("s", $username);
            $qresult = $stmt->execute();    
            if ($qresult) {
                header("Location: second_page.php");
            } else {
                die("Error " . mysqli_error($connection) . " " . "(" . mysqli_errno($connection) . ")" . ", Please contact Sammy for troubleshooting as soon as you can.");
            }
        }
    }
    mysqli_close($connection); //Dont need the connection open anymore

?>
<html>
    <body>     
    <style>...</style>   
        <form name="login" action="login.php" method="POST">
            Username: <input type="text" name="username"></br>
            <input name="submit" type="submit" value="Submit" id="dlbutton" style="cursor:pointer">
        </form>        
    </body>
</html>

Upvotes: 3

Sam
Sam

Reputation: 45

The problem was it is not checking to see if the form was used before executing the statements. Try this:

<?php
if(!empty($_POST)){
$connection = mysqli_connect("localhost", "widget_cms", "password", "widget_corp");
if(mysqli_connect_errno()){
    die("Database connection failed: " . mysqli_connect_error() . "(" . mysqli_connect_errno() . ")");  
}
$username = $_POST['username'];
$username = mysqli_real_escape_string($connection, $username);
$query = "INSERT INTO subjects ( menu_name, position, visible ) VALUES ('{$username}', 4, 1)";
$submission = mysqli_query($connection, $query);
if($submission){
    header("Location: second_page.php");
}
if(!$submission){
    die("Error: " . mysqli_error($connection, $submission));
}
}
?>
<html>
<body>
<form method="post" action="login.php" method="post">
Username: <input type="text" name="username"><br>
<input type="submit" name="submit" id="dlbutton"><br>
</form>
</body>
</html>

Upvotes: 0

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

Firstly and to note: The contents of second_page.php is unknown and whether or not if that is failing you for the file you set in the header. Check for errors in that file also.

So to test, replace the header you have now with a simple echo "Success";

  • Don't use the header and the echo, it will not work.

Here is a slightly different rewrite and make sure you are accessing this on a webserver with both PHP/MySQL installed and accessing as
http://localhost/file.php and not as file:///file.php as an example.

I added error checking to the database connection and for the query and changed the action to action="" for "self", since you're executing inside the same file and a post method for the form, since that was missing.

NOTA: Your menu_name column needs to be long enough to accomodate the ingoing data. MySQL will fail silently if it isn't long enough.

I.e.: Make it VARCHAR (255) to be on the safe side, it's overkill but still a safe bet.

Plus, if you have more columns in your table that we don't know about such as an id for example and is an AUTO_INCREMENT or not, is unknown and if other columns have some form of restraint.

Sidenote: See comments in code.

<?php

error_reporting(E_ALL);  
ini_set('display_errors', 1);

 $connection = mysqli_connect("localhost", "widget_cms", "password", "widget_corp");
 // Make sure you chose the right database and table

 if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>
<html>
<body>
<form name="login" action="" method="post">
Username: <input type="text" name="username"></br>
<input name="submit" type="submit" value="Submit" style="cursor:pointer">
</form>
<?php

if(isset($_POST['submit'])){

    if(!empty($_POST['username']) ){
        $username = $_POST['username'];
        $username = mysqli_real_escape_string($connection, $username);
    }
    else {
        echo "Name is empty.";
        }


      $query = "INSERT INTO subjects (menu_name) VALUES ('{$username}')";

          $qresult = mysqli_query($connection, $query) or die(mysqli_error($connection));
          if($qresult){
               header("Location: second_page.php");
               exit;
               // Replace the header with echo "Success"; but don't use both header and echo
          }else{
               die("Error " . mysqli_error($connection));
          }
     }
?>
</body>
</html>
<?php 
      mysqli_close($connection);
?>

Footnotes:

If this still doesn't work for you, you will need to further investigate your system as to why it's not working, and is beyond the scope of this question.

Upvotes: 0

Martin
Martin

Reputation: 22760

The most likely reason is that you cannot have any HTML before the redirect, try moving all of your php above your html.
-- Epodax

This is why it's not redirecting. Please read about how to use and place PHP Headers.

@Epodax what if i wanted to style it with css though? Can i still do that? -- Sam

If you want a header to redirect to another page, you should have no HTML required because all the output HTML will be in the new, redircted, page.

What you may be wanting to do if you happen for some obscure reason to include the redirect and HMTL from the current page, is to use an include.

Some other notes:

  • Each time you run a header redirect you should end the script with a exit statement directly after it.

  • You need to reformat your code so that NO HTML APPEARS BEFORE THE [potential] REDIRECTION.

  • If you want to style (CSS, etc.) the code in your die() statement it is better to simply replace the die with a varaible and display that variable text on the non-redirected page, informing the user of their error.

  • If there are later issues the redirect is not finding its target properlythen us the FULL URI.

Additional:

(yeah I love bullet points)

  • Use PHP error logging to find your problems and then to solve them. This is fundamental and the one thing you really, really should learn from this issue.

  • Your <form> must use method="post" to send values that will be read by PHP $_POST array. Thanks to Fred-ii for that one. By default the form will send (and PHP will therefore recieve) using GET/$_GET method.

Upvotes: 2

Fabian N.
Fabian N.

Reputation: 1240

You have to move the php-block in front of your html-output. The redirect header (generally all headers) can only be sent, if no output was given yet.

Thus you should make this part

<?php
  $username = $_POST['username'];
  $username = mysqli_real_escape_string($connection, $username);
  $query = "INSERT INTO subjects (menu_name) VALUES ('{$username}')";
  if(isset($_POST['submit'])){
    $qresult = mysqli_query($connection, $query);
    if($qresult){
      header("Location: second_page.php");
    }else{
      die("Error " . mysqli_error($connection) . " " . "(" . mysqli_errno($connection) . ")" .", Please contact Sammy for troubleshooting as soon as you can.");
    }
  }
?>

The very first thing in the script, before output happens.

Upvotes: 0

JiteshNK
JiteshNK

Reputation: 428

your code is working fine just use the method attribute in form.

As you are using POST method to get the value then please use method="POST" as form attribute. Otherwise by default it will take GET method.

Below is the working code. Only few changes made please check and compare

$connection = mysqli_connect("localhost", "root", "", "chat");?>
<html>
<body>
<form name="login" action="index.php" method="POST" >
Username: <input type="text" name="username"></br>

</form>
<?php
if(isset($_POST['username'])){
$username = $_POST['username'];  
$username = mysqli_real_escape_string($connection, $username);
$query = "INSERT INTO users (username) VALUES ('{$username}')";
if(isset($_POST['submit'])){
$qresult = mysqli_query($connection, $query);
if($qresult){
  //header("Location: second_page.php");
}else{
  die("Error " . mysqli_error($connection) . " " . "(" . mysqli_errno($connection) . ")" .", Please contact Sammy for troubleshooting as soon as you can.");
}
 }
}

?>
</body>
</html>
<?php 
mysqli_close($connection);
?>

Upvotes: 1

Related Questions