【问题标题】:html form submit calls a php but does not redirect [duplicate]html表单提交调用php但不重定向[重复]
【发布时间】:2015-12-11 16:47:17
【问题描述】:

好的朋友们,我对这个基本的东西很困惑。我已经阅读了很多帖子,上面写着,我需要添加 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">

提交.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})$/') 电话正则表达式 (^(?:(?:\+|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 (input type="email") 在您转到下一个字段后立即显示无效的电子邮件警报,就在该字段的下方。怎么可能在所有领域都做到这一点? (类似于字段丢失焦点的验证检查)

谢谢

【问题讨论】:

  • 你的重定向在哪里?
  • 首先了解一下sql注入。其次 - 不推荐使用 mysql,请改用 mysqli 或 PDO。第三 - 将 index.html 重命名为 index.php,在 submit.php 之后 mysql_close($con) 添加 header("Location: localhost/index.html?success=1 (or what url do you have)")。在 index.php 添加 1 记录添加
  • 你有一个语法错误,你很可能在标题之前输出

标签: php mysql forms http-post


【解决方案1】:

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

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

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:
例如&lt;input type="email" name="email"&gt;

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

您的验证应该在 submit.php 中进行。如果您要在应用程序中包含更多表单,您可以考虑将服务器端验证功能放在单独的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; ?>"/>

【讨论】:

  • 感谢您的回复。这真让我抓狂。我完全按照您所说的方式进行了操作,但它只是显示了一个空白的 submit.php 文件,并且数据没有进入数据库,没有警报,没有重定向,什么都没有……我检查了三遍。我不知道我做错了什么。我需要在 submit.php 文件中放置 html 正文和其他标签吗?我所有的文件(index.html、submit.php 和 config.php 都在同一个文件夹中)
  • 编辑了我的答案。我忘了在 $con->query($sql) 之后关闭一个括号......还为所有 POST 字段添加了转义。至少现在它对我有用。
  • 我花了一点时间才明白你说的是哪个右括号,但最终明白了。它现在工作。感谢您的帮助
  • 按照您的建议,在重定向到 index.html 之前,我正在尝试脚本检查失败,但验证很少,但为此苦苦挣扎。我有一个用于电子邮件的正则表达式 ('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0 -9-]+)*(\.[az]{2,3})$/') 和电话 (^(?:(?:\+|0{0,2})91(\s*[\ -]\s*)?|[0]?)?[789]\d{9}$) 但不知道如何正确处理。不知道是客户端还是服务器端和语法。我用
  • 再次感谢您的帮助,但我仍然觉得有点困难,想知道在哪里添加验证。我已经编辑了我的原始帖子。感谢您是否可以看看它。谢谢
【解决方案2】:

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

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

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

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

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

【讨论】:

  • 感谢您的参考。我会在一段时间内阅读它。对于像我这样的新手来说,第二个选项看起来有点困难 LOL
【解决方案3】:

index.html

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

提交.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")
}
?>

【讨论】:

  • 感谢您的回复。我试过了,但数据没有进入数据库。它只是显示一个空白的 submit.php 页面。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 1970-01-01
  • 2016-09-22
  • 2013-09-10
  • 1970-01-01
相关资源
最近更新 更多