html 表单提交调用 php 但不重定向

html form submit calls a php but does not redirect

好的朋友,我对这个基本的东西很困惑。我读过很多帖子说,我需要添加 SELF POST 或其他东西,但我不明白。

我有两个文件,index.html 和 submit.php。 index.html 有一个带有提交按钮的表单,单击该按钮会调用 submit.php 文件并显示一条消息“已添加 1 条记录”。我想从 submit.php 文件重定向回 index.html 文件。我不知道我做错了什么。是不是因为一个是html文件,另一个是php?请帮忙。这是我的代码

index.html 文件

<form method="post" action="submit.php">

submit.php 文件

    <?php
    $con = mysql_connect("localhost","myuser","mypassword");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    mysql_select_db("mydb", $con);
    $sql="INSERT INTO members (sName, sCity, sMobile, sEmail, sSub, sSlogan)
    VALUES ('$_POST[name]', '$_POST[city]', '$_POST[mobile]', '$_POST[email]', '$_POST[sub]', '$_POST[slogan]')";
    if (!mysql_query($sql,$con))
      {
      die('Error: ' . mysql_error());
      }
    echo "1 record added";
    mysql_close($con)
    ?>
    </body>
</html>

编辑

请查找 index.html 和 submit.php 文件的代码。在您的帮助下,两者都能完美运行。我仍在努力将验证码放在哪里。我在 html 文件中使用 html5 种输入类型,但我不知道在 submit.php 文件中确切发生验证的位置。是的,我确实有多种表格,并且我按照您的建议制作了 validations.php 文件。我不明白的是,如果 validations.php 文件中的名称字段具有 validate_name($input) 函数,那么为什么要在 submit.php 中再次验证名称? ( if (!empty($_POST['name']) )。我也不明白错误消息会显示在哪里?如果我尝试添加这些功能,它会给我空白页点击提交,数据没有进入数据库。

您能否在 submit.php 文件中建议我应该通过编辑 submit.php 文件来添加这些验证的位置? 电子邮件正则表达式 ('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/') phone (^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$)

的正则表达式

这是我的index.html文件

<!DOCTYPE HTML>
<html>

<head>
    <title>My Title</title>
</head>

<body>

    <form method="post" action="submit.php">
        <div class="box">
            <div class="cl"><input type="text" name="name" placeholder="Name" /></div>
            <div class="cl"><input type="text" name="city" placeholder="City" /></div>
            <div class="cl"><input type="text" name="mobile" placeholder="Mobile" /></div>
            <div class="cl"><input type="email" name="email" placeholder="Email" /></div>
            <div class="cl"><input type="text" name="sub" placeholder="Want 3 m Free Subscription (Yes/No)?"></textarea></div>
            <div class="cl"><input type="text" name="slogan" placeholder="Suggest a slogan for 6 m subscription"></textarea></div>
        </div>

        <div class="srow">
            <div class="cl1">
                <ul class="action">
                    <li><input type="submit" value="Submit" /></li>
                </ul>
            </div>
        </div>
    </form>
</body>

</html>

这是我从您那里得到的submit.php文件帮助

<?php
include 'config.php'; // store your configuration in a seperate file so 
                      // you only need to update it once when your environment changes

$errors = false;
$output = '';
$nl = '<br>'.PHP_EOL;
$redirect_url = 'index.html';

if (!$con = new mysqli(DBHOST,DBUSER,DBPASS,DBNAME)){
    $errors = true;
    $output .= "ERROR Can't connect to DB".$nl;
};   


if (!$errors){
   //should validate/clean $_POST before using in query
   $name = $con->escape_string($_POST['name']);
   $city = $con->escape_string($_POST['city']);
   $email = $con->escape_string($_POST['email']);
   $mobile = $con->escape_string($_POST['mobile']);
   $sub = $con->escape_string($_POST['sub']);
   $slogan = $con->escape_string($_POST['slogan']);

   $sql="INSERT INTO members 
            (sName, sCity, sMobile, sEmail, sSub, sSlogan)
         VALUES ('$name', '$city', '$mobile', '$email',
                '$sub','$slogan')";

   if (!$con->query($sql)){ //forgot a parenthesis here earlier
      $output .= 'ERROR: DB said: ('.$con->errno.') '.$con->error.$nl;
      $output .= 'Query was:'.$sql.$nl;
      $errors = true;
   }else{
     $output .= "1 record added".$nl;
   }
}

if (!$errors){
   //if there are no errors redirect to index.html;
   header('refresh: 2; URL='.$redirect_url);
   $output .= '...Redirecting...'.$nl;
}else{
   //show the errors and allow display a link to go back/try again
   $output .= '<a href="'.$redirect_url.'">Try again</a>'.$nl;
}
echo $output;
?>

PS:我观察到的一件事是 html5(输入类型="email")在您转到下一个字段后立即显示无效电子邮件警报,就在该字段下方。怎么可能对所有领域都做到呢? (类似于字段丢失焦点的验证检查)

谢谢

提交表单时,浏览器会跳转到form标签的target属性指定的页面,在你的情况是 submit.php.

  1. 处理完 POST 数据后,您的提交页面应该呈现一些内容,重定向回 index.html,备选方案:

  2. 如果不想重新加载页面,应该使用AJAX向服务器发送数据:

    • 你应该在提交按钮上设置一个监听器,
    • 一键发送数据,
    • 您还应该禁用默认操作(即跳转到目标页面)。

首先你应该尝试第一个,它更容易。

index.html

<form method="post" action="submit.php">
    //Html Codes
</form>

submit.php

<?php
$con = mysql_connect("localhost","myuser","mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);

$sql="INSERT INTO members (sName, sCity, sMobile, sEmail, sSub, sSlogan)
VALUES ('$_POST[name]', '$_POST[city]', '$_POST[mobile]', '$_POST[email]', '$_POST[sub]', '$_POST[slogan]')";
if (!mysql_query($sql,$con))
{
    die('Error: ' . mysql_error());
}
else
{
    header("location:index.html?Message=Success")
}
?>

您可以让您的提交脚本检查失败并重定向到 index.html 以在成功时添加更多内容。

请记住,在使用 echo 输出任何其他数据之前,您必须设置 header。

header('refresh: 3; URL=index.html');

不要使用mysql,使用mysqli或PDO。

了解 SQL 注入。

所以你的 sumbit.php 可能看起来像:

<?php
include 'config.php'; // store your configuration in a seperate file so 
                      // you only need to update it once when your environment changes

$errors = false;
$output = '';
$nl = '<br>'.PHP_EOL;
$redirect_url = 'index.html';

$con = new mysqli(DBHOST,DBUSER,DBPASS,DBNAME);

if ($con->connect_errno){
    $errors = true;
    $output .= "ERROR Can't connect to DB".$nl;
};

if (!$errors){
   //should validate/clean $_POST before using in query
   $name = $con->escape_string($_POST['name']);
   $city = $con->escape_string($_POST['city']);
   $email = $con->escape_string($_POST['email']);
   $mobile = $con->escape_string($_POST['mobile']);
   $sub = $con->escape_string($_POST['sub']);
   $slogan = $con->escape_string($_POST['slogan']);

   $sql="INSERT INTO members 
            (sName, sCity, sMobile, sEmail, sSub, sSlogan)
         VALUES ('$name', '$city', '$mobile', '$email',
                '$sub','$slogan')";

   if (!$con->query($sql)){ //forgot a parenthesis here earlier
      $output .= 'ERROR: DB said: ('.$con->errno.') '.$con->error.$nl;
      $output .= 'Query was:'.$sql.$nl;
      $errors = true;
   }else{
     $output .= "1 record added".$nl;
   }
}

if (!$errors){
   //if there are no errors redirect to index.html;
   header('refresh: 2; URL='.$redirect_url);
   $output .= '...Redirecting...'.$nl;
}else{
   //show the errors and allow display a link to go back/try again
   $output .= '<a href="'.$redirect_url.'">Try again</a>'.$nl;
}
echo $output;

config.php 将包含

define('DBHOST','localhost');
define('DBUSER','myuser');
define('DBPASS','secretpass');
define('DBNAME','mydb');

编辑/补充:

如果您想进行一些验证,在客户端进行一些验证会很有帮助,这样当您已经知道某些输入不符合要求时,您的用户不必提交并被拒绝。

但您还需要在服务器端进行验证(不良用户可以通过在浏览器中编辑 html 来绕过您可能拥有的任何客户端验证)

为了帮助您的用户,您可以使用一些可用的新 html5 input types,也可以选择使用一些额外的 javascript:
例如<input type="email" name="email">

您的 index.html 可以保留为静态页面。它仅显示输入表单,并可能加载一些 javascript 资源以进行验证。

您的验证应该在 submit.php 中进行。如果您要在应用程序中包含更多表单,您可以考虑将 server-side 验证函数放在单独的 validations.php 中,您可以将其包含在 submit.php

它可能包含如下函数:

function validate_name($input){
    // fairly naive rule:
    // upper and lower case latin characters and space
    // at least three character long
    // you may want to look at allowing other characters such as é ö etc.
    $input = trim($input); //get rid of spaces at either end
    if (preg_match('/^[a-zA-Z ]{3,}$/',$input) == 1){
        return $input;
    }else{
        return false;
    }
}

在你的submit.php中你可以

...
include_once 'validations.php';
...

  if (!empty($_POST['name'])){
    if (!$name = $con->escape_string(validate_name($_POST['name'])){
        $errors = true;
        $output .= 'ERROR: Invalid Name: '.$_POST['name'].$nl;
    }
  }else{
    $errors = true;
    $output .= 'ERROR: No name specified'.$nl;
  }

  if (!empty($_POST['city']){
    ...

...

要获取已输入的数据以在出现故障时进行填充,您可以通过 GET 参数将数据发送回原始数据。

在 submit.php 中,您可以在接近尾声时添加类似 ...

的内容
if (!$errors){
   //if there are no errors redirect to index.html;
   header('refresh: 2; URL='.$redirect_url);
   $output .= '...Redirecting...'.$nl;
}else{
   //show the errors and allow display a link to go back/try again
   //add parameters to show the data already entered
   $redirect_url .= '?'.
        http_build_query(
                  array('name'=>$name,
                        'city'=>$city,
                        'mobile'=>$mobile,
                        ...
         ));

   $output .= '<a href="'.$redirect_url.'">Try again</a>'.$nl;
}
echo $output;

在 index.php 中,您必须阅读它们并在输入字段中设置值(如果存在)。

<?php 
//we'll use urldecode() so that any special characters will be interpreted correctly
if (!empty($_GET['name'])){
    $name = urldecode($_GET['name']);
}else{
    $name = '';
}
if (!empty($_GET['city'])){
    $city = urldecode($_GET['city']);
}else{
    $city = '';
}
....
?>
<input type="text" name="name" value="<?php echo $name; ?>"/>
<input type="text" name="city" value="<?php echo $city; ?>"/>