How to refresh the site to another page in php

时间:2017-06-09 12:51:39

标签: php mysql

I have a file called inser_product.php which is where I have the function to insert products into the database table.

The function to insert the products looks like this:

<?php
include 'db.php';
function insert_product(){
    try{
        global $conn;

        //prepare sql and bind parametes

        $statement = $conn->prepare("insert into products (product_name, product_price, product_description) value (:product_name, :product_price, :product_description)");
        $statement ->bindParam(':product_name', $product_name);
        $statement ->bindParam(':product_price', $product_price);
        $statement ->bindParam(':product_description', $product_description);

        // executing the statement

        $product_name = $_POST['product_name'];
        $product_price = $_POST['product_price'];
        $product_description = $_POST['product_description'];

        $statement->execute();

        header('Location: index.php');
    }
    catch(PDOException $e){
        echo $query . "<br>" . $e->getMessage();
    }
    $conn = null;
}
?>

Then I used the post method for the button and call the insert_product function:

<?php
if(isset($_POST['submit-button'])){
    insert_product();
}
?>

All the insertion works fine but, How can I redirect the page to my index.php after all the data is inserted?

As you can see I used the code below but it does not work.

echo "<script>window.open('index.php','_self')<script>";

3 个答案:

答案 0 :(得分:0)

try{
    $query = "insert into products(product_name, product_price, product_description) values ('$product_name','$product_price','$product_description')";
    $conn->exec($query);
    header('Location: index.php');
}

答案 1 :(得分:0)

You can use header() of php. But make sure there must be not echo or print before it

<?php
    if(isset($_POST['submit-button'])){
        insert_product();

        header('Location: index.php');
    }
?>

答案 2 :(得分:-1)

对于php使用:

header('location: index.php');

对于JavaScript使用

window.location.href='index.php';
相关问题