简体   繁体   English

PHP URL重定向无法按预期工作

[英]PHP URL redirection not working as expected

I am having a problem loading a fresh "thankyou.php" file after a form has been submitted. 提交表单后,加载新的“ thankyou.php”文件时出现问题。 The form sends data to itself and if all the data passes validation it then proceeds to save them in the database. 表单将数据发送给自身,如果所有数据均通过验证,则它将继续将其保存在数据库中。

The "thankyou.php" quite loads but the "signup.php" still remains and the output of both files remain in the same page. “ thankyou.php”已完全加载,但“ signup.php”仍然保留,并且两个文件的输出保留在同一页面中。 I want it on a fresh page but it won't work. 我想要一个新的页面,但是它不起作用。

Here is my sanitation: 这是我的卫生条件:

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["firstName"]))
{$Err[] = "* First Name is required";}
else
{
$name = test_input($_POST["firstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
  {
  $Err[] = "Only letters are allowed in First Name"; 
  }
}

if (empty($_POST["email"]))
{$Err[] = "* Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
  {
  $Err[] = "Invalid email format"; 
  }
}   
}

And the form: 以及形式:

<div id = "signupform">

" > Email Address First Name “>电子邮件地址的名字

And database connection and insertion: 与数据库连接和插入:

try {
  $conn = new PDO('mysql:host=localhost; dbname=mydb', 'root', ''); 
  $conn->setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

catch(PDOException $pe) { echo('Connection error, because: ' .$pe->getMessage()); catch(PDOException $ pe){echo('连接错误,因为:'。$ pe-> getMessage()); } }

//Insert data to Database if values are not empty and sanitized if (!empty($_POST["firstName"]) && !empty($_POST["email"])) { $qry = "INSERT INTO userdetails (email, firstName) values (?, ?)"; //如果值不为空,则将数据插入数据库,如果((empty($ _ POST [“ firstName”])&&!empty($ _ POST [“ email”]))){{qqry =“ INSERT INTO userdetails(email, firstName)值(?,?)“;

$q = $conn->prepare($qry) or die("ERROR: " . implode(":", $conn->errorInfo()));

$q->bindParam(1, $email);
$q->bindParam(2, $firstName);


try {
  if($q->execute()){
    header("Location: invoice.php");
    exit;
  }
  }
catch(PDOException $pe) {
  echo('Connection error, because: ' .$pe->getMessage());
}

} }

And that's all but it is still not loading a fresh page. 仅此而已,但它仍未加载新页面。

I think the problem is you are calling $q->execute() twice, try this: 我认为问题是您两次调用$q->execute() ,请尝试以下操作:

try {
    if ($q->execute()){
        header("Location: thankyou.php");
        exit;
    }
} catch(PDOException $pe) {
    echo('Connection error, because: ' .$pe->getMessage());
}

After more digging up and more understanding of what you are actually doing (the wrong way), I came up with my solution. 在深入挖掘并进一步了解您的实际操作(错误的方式)之后,我提出了解决方案。 Pretty much you need to make it so that the MySQL insert statements were a part of the error validation not stand-a-lone. 您几乎需要这样做,以使MySQL插入语句成为错误验证的一部分,而不是独立的。 If you look at my prior code the PDO statements had no real place in the code, it was just there. 如果您看一下我以前的代码,PDO语句在代码中没有实际位置,就在那里。

However, if it is true that there are no $Err , it will run the insert script with a error check for that script. 但是,如果确实没有$Err ,它将运行插入脚本并对该脚本进行错误检查。 Then if it inserts correctly, it will then redirect the user to the next page. 然后,如果正确插入,它将把用户重定向到下一页。

For validation code, check with the submit button. 有关验证代码,请单击提交按钮。

if(isset($_POST["submit"])){if (empty($_POST["firstName"])){$Err[] = "* First Name is required";}else{$name = test_input($_POST["firstName"]);if (!preg_match("/^[a-zA-Z ]*$/",$name))  {  $Err[] = "Only letters are allowed in First Name";   }}if (empty($_POST["email"])){$Err[] = "* Email is required";}else{$email = test_input($_POST["email"]);if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)){  $Err[] = "Invalid email format";   }}   }

Validated error message: 验证错误消息:

if (empty($Err) === false) {
        echo '<h3>';
        foreach ($errors as $Err) {
            echo '<center><li>', $error, '</li></center>';
        }

        echo '< h3 >';
    }

Your HTML form should be like this: 您的HTML表单应如下所示:

<form method="post"  action ="echo $_SERVER['PHP_SELF'];"><table >        
<tr><td>Email Address < input type="text"  name="email" value="email" ></td>
</tr><tr valign="baseline"> 
  <td>First Name <br/>< input type="text" name="firstName" value="" ></td>
</tr>
<input type="submit" value="submit" name="submit">
</form>

Now the server-side query operation will execute with validated only: 现在,服务器端查询操作将仅在经过验证的情况下执行:

try {
    $conn = new PDO('mysql:host=localhost; dbname=mydb', 'root', ''); 
    $conn->setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $pe) {
    echo('Connection error, because: ' .$pe->getMessage());
}if (!empty($_POST["firstName"]) && !empty($_POST["email"])){
$qry = "INSERT INTO userdetails (email, firstName) values (?, ?)";
$q = $conn->prepare($qry) or die("ERROR: " . implode(":", $conn->errorInfo()));
$q->bindParam(1, $email);
$q->bindParam(2, $firstName);
try {
    if($q->execute()){

// You can use Two Way to Redire Server side Depending on version

       // http_redirect("invoice.php");
       //OR (Above & below any 1 line can be workout for you.
        header("Location: invoice.php");
        exit;
    }
    }
catch(PDOException $pe) {
    echo('Connection error, because: ' .$pe->getMessage());
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM