首页 > 解决方案 > 插入数据后的PHP重定向

问题描述

我在插入数据后重定向到另一个页面时遇到问题。

我正在本地主机上工作,我试图在插入数据后重定向到另一个页面(url)。

使用下面的代码,我尝试将 google url 它不会重定向它在提交后保留在页面上。

任何帮助,将不胜感激。

谢谢

<?php
/**
 * Template Name: Booking Template
 */
get_header();

require_once("db.php");

if(count($_POST)>0) {
$sql = "INSERT INTO bookings (reason, doctor, bookingDate, bookingTime, patientName, gender, phone, email) VALUES ('" . $_POST["reason"] . "','" . $_POST["doctor"] . "','" . $_POST["bookingDate"] . "','" . $_POST["bookingTime"] . "','" . $_POST["patientName"] . "','" . $_POST["gender"] . "','" . $_POST["phone"] . "','" . $_POST["email"] . "')";

  if(mysqli_query($link, $sql)){
    echo "Records inserted successfully.";
    header("location: http://www.google.com");	
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
mysqli_close($link);
?>

标签: phpsql

解决方案


如果您在header()不会重定向之前回显或打印某些内容。所以你需要删除echo之前的header(). exit()header(). _

/**
 * Template Name: Booking Template
 */
get_header();

require_once("db.php");

if(count($_POST)>0) {
$sql = "INSERT INTO bookings (reason, doctor, bookingDate, bookingTime, patientName, gender, phone, email) VALUES ('" . $_POST["reason"] . "','" . $_POST["doctor"] . "','" . $_POST["bookingDate"] . "','" . $_POST["bookingTime"] . "','" . $_POST["patientName"] . "','" . $_POST["gender"] . "','" . $_POST["phone"] . "','" . $_POST["email"] . "')";

  if(mysqli_query($link, $sql)){
    //echo "Records inserted successfully."; remove or comment this line
    header("location: http://www.google.com");
    exit(); // use exit. It's a good practice
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
mysqli_close($link);

如果您的查询正常并且数据插入正确但尚未重定向,您可以使用Javascript重定向。

/**
 * Template Name: Booking Template
 */
get_header();

require_once("db.php");

if(count($_POST)>0) {
$sql = "INSERT INTO bookings (reason, doctor, bookingDate, bookingTime, patientName, gender, phone, email) VALUES ('" . $_POST["reason"] . "','" . $_POST["doctor"] . "','" . $_POST["bookingDate"] . "','" . $_POST["bookingTime"] . "','" . $_POST["patientName"] . "','" . $_POST["gender"] . "','" . $_POST["phone"] . "','" . $_POST["email"] . "')";

  if(mysqli_query($link, $sql)){
    //echo "Records inserted successfully."; remove or comment this line
    header("location: http://www.google.com");
    echo "<script>window.location = 'http://www.google.com';</script>";
    exit(); // use exit. It's a good practice
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
mysqli_close($link);

确保函数没有错误,get_header()并仔细检查代码中是否存在任何可能的错误。仅当您现在需要解决它时才使用第二种方法。


推荐阅读