HTML表单提交调用PHP,但不重定向



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

我有两个文件,index.html和submit.php。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的代码并提交.php文件。在你的帮助下,两者都很完美。我仍然在努力,确切地把验证代码。我在html文件中使用html5输入类型,我不知道在哪里验证发生在提交。php文件。是的,我确实有多个表单,我做了validations.php文件建议你。我不明白的是,如果你有函数validate_name($input)的名称字段在validations.php文件那么为什么你验证的名称再次提交。php?(if (!empty($_POST['name']))。我也不明白在哪里会显示错误信息?如果我尝试添加这些功能,它会在点击提交时给我空白页面,数据不会进入数据库。

你能建议在submit.php文件中的一个位置,我应该通过编辑我的submit.php文件添加这些验证吗?Regexp for email ('/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/')Regexp for 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>

这是我从你那里得到的提交。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")显示无效的电子邮件警报后,你去下一个字段,就在字段下。如何在所有领域都做到这一点呢?(类似于字段失去焦点的验证检查)

谢谢

您可以让您的提交脚本检查失败,并重定向到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');

EDIT/add:

如果你想做一些验证,在客户端做一些是有帮助的,这样当你已经知道一些输入不符合时,你的用户就不必提交和被拒绝了。

但是你还需要在服务器端进行验证(坏用户可以通过在他们的浏览器中编辑html来绕过任何客户端验证)

为了帮助你的用户,你可以使用一些新的html5输入类型,可以选择使用一些额外的javascript:
例:<input type="email" name="email">

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; ?>"/>

当你提交一个表单时,浏览器会跳转到在表单标签的target属性中指定的页面,在你的例子中是submit.php

  1. 处理POST数据后,您的提交页面应该呈现一些东西,它重定向回index.html,替代:

    • 头http://php.net/manual/en/function.header.php
    • HTML "meta"标签https://en.wikipedia.org/wiki/Meta_refresh
  2. 如果您不想重新加载页面,您应该使用AJAX向服务器发送数据:

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

你应该先试试第一个,比较简单。

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

最新更新