PHP 移动到部分

PHP move to section

好的,所以我有一个 PHP 脚本,它是一个联系表(如下所示)

$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($_POST['submit']) {
if ($name != '' && $email != '') {
    if ($human == '4') {                 
        if (mail ($to, $subject, $body, $from)) { 
        echo '<p>Your message has been sent!</p>';
    } else { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    } 
} else if ($_POST['submit'] && $human != '4') {
    echo '<p>You answered the anti-spam question incorrectly!</p>';
}
} else {
    echo '<p>You need to fill in all required fields!</p>';
  }
 }
?>    

我想知道(因为我在 PHP 方面不是很有经验)如果出现错误,是否有办法让我回到 div 联系表格所在的位置? 提前致谢 编辑:HTML 代码: http://pastebin.com/CwXsDapB

是的,您可以将错误存储在会话中。

然后再次重定向到表单。

例如

$_SESSION['error'] = '<p>Something went wrong, go back and try again!</p>';
header("Location:YOUR_FORM.PHP?error#form_div");

将添加 ID form_div 添加到包含您的表单的 div。

<div id="form_div">
<?php
if (! empty($_SESSION['error'])) {
  echo $_SESSION['error'];
  $_SESSION['error'] = '';
}
?>
<form>

...

是的,您可以在出现错误时返回联系表, 您的联系表是在同一页还是另一页?

如果在同一页面上,那么我建议您使用 Javascript 或 Jquery 的验证,这将检查表单是否具有值并且值是否等于任何数字,然后成功后,您可以提交表格。

下面的link可以帮助你验证,

http://www.tutorialspoint.com/cgi-bin/practice.cgi?file=javascript_43

如果您需要使用 PHP 并且在提交表单后进入不同的页面,您可以使用

header 来自 PHP 的函数使其重定向到表单页面。

http://php.net/manual/en/function.header.php

此致, V

不需要 PHP 会话,因为您正在同一页面中处理表单(看到您有 <form method="POST"> )。

例如,将您的返回消息存储在 $status 变量中,然后在表单和您的 php 页面之前将其显示为:

<?php
    $body = "From: $name\n E-Mail: $email\n Message:\n $message";
    if ($_POST['submit']) {
        if ($name != '' && $email != '') {
            if ($human == '4') {                 
                if (mail ($to, $subject, $body, $from)) { 
                $status =  '<p>Your message has been sent!</p>';
            } else { 
                $status = '<p>Something went wrong, go back and try again!</p>'; 
            } 
        } else if ($_POST['submit'] && $human != '4') {
            $status = '<p>You answered the anti-spam question incorrectly!</p>';
        }
        } else {
            $status = '<p>You need to fill in all required fields!</p>';
        }
    }
    echo ($status) ? '<div id="status">'.$status.'</div>' : '';
?>
<form action="" method="POST"> 
        <label>Name</label>
        <br>
        <input name="name" placeholder="Type Here">
    </div>
    <div>   
        <label>Email</label>
        <br>
        <input name="email" type="email" placeholder="Type Here">
    </div>
    <div>
        <label>Message</label>
        <br>
        <textarea name="message" placeholder="Type Here"></textarea>
    </div>
    <div> 
        <label>*What is 2+2? (Spam protection)</label>
        <br>
        <input name="human" placeholder="Type Here">
    </div>

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