0

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.

Hamza Zafeer
  • 2,360
  • 13
  • 30
  • 42
Sam
  • 45
  • 2
  • 8
  • It really helps if you provide a minimal example of your code which shows the issue, the style here is irrelevant and will most likely cause a lot of people to simply not read the question and not provide any help. – apokryfos Mar 31 '16 at 11:39
  • @apokryfos oh ok ill change it – Sam Mar 31 '16 at 11:41
  • 3
    The most likely reason is that you cannot have any HTML before the redirect, try moving all of your php above your html. – Epodax Mar 31 '16 at 11:42
  • @Epodax what if i wanted to style it with css though? Can i still do that? – Sam Mar 31 '16 at 11:44
  • instead of `header` you can use javascript to redirect your page `echo ""` – Shri Suresh Mar 31 '16 at 11:46
  • 1
    you forgot to quit the script (`exit;`) after the redirect – Daniel W. Mar 31 '16 at 11:46
  • @Sam once you find a solution click the tick under the answer that helped you, to resolve the question and show future visitors what was the solution. Cheers – Martin Mar 31 '16 at 12:34
  • I won't post more comments under other answers as they all missed a very important factor of the OP's code failing. – Funk Forty Niner Apr 01 '16 at 23:19
  • Yep it still doesnt redirect or insert into mysql. – Sam Apr 01 '16 at 23:39
  • 1
    @Sam If it doesn't redirect, then you may be outputting before header and THAT is where error reporting comes in. Add error reporting to the top of your file(s) right after your opening PHP tag for example ` – Funk Forty Niner Apr 01 '16 at 23:40
  • @Sam You also should add `exit;` after the header, otherwise your code may want to continue to execute. Now, you are using this on a hosted site, or is it on your own computer? – Funk Forty Niner Apr 01 '16 at 23:43
  • @Fred-ii- i added it, still doesnt work. Its on my own computer. And error reporting is alrealdy on, the only error i get is `Notice: Undefined index: username in C:\xampp\htdocs\login.php on line 48` – Sam Apr 02 '16 at 04:07
  • @Sam That I had a feeling you would get, since you're using your entire code in the same file with no conditional checks. – Funk Forty Niner Apr 02 '16 at 12:43
  • @Fred-ii- thats not the problem. I think its just that its all executing before i press the "submit". And its also not inserting into mysql. Im very new to this so dont expect me to know too much. – Sam Apr 02 '16 at 14:19
  • Yes it is the problem. – Funk Forty Niner Apr 02 '16 at 14:19
  • @Sam I added an answer for you to look at below. If that still doesn't work for you, then there isn't anything else I can do, except to be sitting next to you *lol* – Funk Forty Niner Apr 02 '16 at 17:00
  • @Fred-ii- I got it myself actually, but thanks. – Sam Apr 03 '16 at 01:19

6 Answers6

3

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>
apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • I have no idea why this was upvoted so many times, as it's incorrect and failing silently for the OP. – Funk Forty Niner Apr 01 '16 at 23:17
  • @Fred-ii- is right, i didnt know i had to let you know but the code is still failing. – Sam Apr 01 '16 at 23:36
  • @Sam Reason being is that forms default to a GET method if POST isn't implied. `
    ` needs to read as `
    ` and strangely enough, even having error reporting set to catch and display, won't throw an error about it. An oversight by the crew at PHP.net I'd say.
    – Funk Forty Niner Apr 01 '16 at 23:39
2

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.

Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132
  • You also missed something in the OP's code that is failing ever so *silently*. – Funk Forty Niner Apr 01 '16 at 23:18
  • Not declaring the form to send via `method=post`? haha, I enjoy the frustration of reading you comment and then finding the objective. @Fred-ii- – Martin Apr 01 '16 at 23:29
  • Yepper! Another answer was given where he/she mentioned it and he/she was downvoted for it and I can't see what someone did. Now the OP reposted a new / same question minutes ago http://stackoverflow.com/q/36367231/ but I probably won't be posting an answer for it. If the OP couldn't resolve already, then I might get chased down a very deep rabbit hole. After a full day of coding, I honestly don't have the energy for it ;-) – Funk Forty Niner Apr 01 '16 at 23:33
  • @Fred-ii- I sympathise entirely. Sometimes it's too much effort to tell people of the multiple issues causing their problems. I know some seasoned SO members have copy/paste replies, I should get into doing that. But my problem is I hate to only half correct code. haha. I'm maybe code OCD. – Martin Apr 01 '16 at 23:36
  • Thing is about not having a specific "post" method and I learned this not long ago (yeah... *duh* on my part... *sort of*) that error reporting won't catch that as an error, go figure huh? A slight oversight on the part of the crew at PHP.net? – Funk Forty Niner Apr 01 '16 at 23:36
  • @Fred-ii- not really, I think that's why there's the catchall `$_REQUEST` method which accepts both (and possibly `$_COOKIE` as well?) – Martin Apr 01 '16 at 23:37
  • @sam, edit your original post, put a clear barrier between the original question and then undeneath put the updated code edit and more info. about why it's not working. Did you use PHP Errror logging? – Martin Apr 01 '16 at 23:39
  • @Martin Yes, using `$_REQUEST` might catch all but only if the OP were to change all of the `$_POST`s to that. However, I'd steer away from that, especially when it comes to db stuff. I've been contradicted about no differences with GET/POST, but I beg to differ. Even the higher rep than I don't know everything ;-) – Funk Forty Niner Apr 01 '16 at 23:42
  • @Fred-ii- yeah the POST/GET ambiguity is almost as if people who create the language expect those who write the language to know what they're doing! haha. And I never use `$_REQUEST`, I percieve it as lazy (and opens a significant hole in source reliability (not that input should ever be trusted anyway)). – Martin Apr 01 '16 at 23:45
1

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);
?>
JiteshNK
  • 428
  • 2
  • 11
0

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.

Martin
  • 22,212
  • 11
  • 70
  • 132
Fabian N.
  • 1,221
  • 10
  • 18
  • I think removing the word "generally" from the headers statement would be a really good idea. No [page] header accepts output *before* the header. – Martin Mar 31 '16 at 12:04
  • @Martin https://en.wiktionary.org/wiki/generally (Adverb, point 2: As a rule; usually) – Fabian N. Mar 31 '16 at 12:15
  • it's not a *usually*, it is an always. Can you find a PHP Header for a page that is happy to display *after* page content has been output to the browser? Therefore the term "generally" adds needless ambiguity. – Martin Mar 31 '16 at 12:20
0

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.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

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>
Sam
  • 45
  • 2
  • 8