开发者

Prevent PHP from running until POST

So I'm really really really new to PHP and MySQL (just started today!).

I have a page that updates a MySQL database based on results from a post.

The way I have it now, the PHP code is on the page, and it works, but the problem is that it goes through on page load as well, that is, before the POST happens.

Any way to prevent this?

Here's my code:

        <?php
            //do stuff

        开发者_如何转开发    // see if any rows were returned
            if (mysql_num_rows($result) > 0) {

                $row = mysql_fetch_row($result);

                while($row = mysql_fetch_row($result)) {
//do something
                  }
            }
            else {
//do something else
            }

            // free result set memory
            mysql_free_result($result);
            $first = 0;
        ?>
        <br />
        <br />

          <div id="addName">  
            <h3 class="caps">Want to add yourself?</h3>  

            <div class="box">  

            <br /> <br />
            <form id="form1" name="form1" method="post" action="#">

            Email:
            <label>
            <input type="text" name="email" id="email" />
            </label>

              <label>
              <input type="submit" name="submit" id="submit" value="Submit" />
              </label>

            </form>
            </div>  

          </div>  

        </div>  

See, problem is that it will run //do something else before the form is filled out. Any suggestions?

Thanks!


Better Condition

if(isset($_POST['submit']) && !empty($_POST) ){
  // now do with your post data
}

this will prevent empty data to be posted


if(isset($_POST['submit'])){
  // do things when post has been made
  // e.g. insert the data into SQL
}

Take a read of this page. The above code will check to make sure the submit button has been pressed.


If you are hosting the HTML form on a different page you can put this at the top of your code on the PHP page. It will redirect the user to the HTML form file before any code is executed.

if (!$_POST['submit']) {
   header("Location: ./form.html");
   die();
}

However if you prefer to keep the form on the same page (which it looks like you are) you can use the suggestions above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜