如何摆脱PHP表单重定向

时间:2013-09-25 23:22:34

标签: php html mysql

将数据插入MySQL后,我被重定向到PHP文件。不酷!如何在同一HTML文件中显示错误或成功消息。

的index.html

<form id="form" action="add_article.php" method="post">
    <div class="span4">
        <div class="control-group">
            <input type="text" placeholder="title" name="title"><br/><br/>
            <input type="text" placeholder="author" name="author"><br/><br/>
            <textarea placeholder="article summary" rows="12" maxlength="300" name="description"></textarea><br/><br/>
            <input type="text" placeholder="location e.g. lubaga cathedral" name="location"><br/><br/>
        </div>
</form>

add_article.php

<?php
    $con=mysqli_connect("localhost","root","","bookdb");

    if (!$con){
        die ("Failed to connect to MySQL: " . mysqli_connect_error($con));
    }
    $sql = "INSERT INTO article (title, author, description,location)
    VALUES('$_POST[title]','$_POST[author]','$_POST[description]','$_POST[location]')";

    if(mysqli_query($con,$sql))
        echo "Article inserted";
    else
        echo "An Error was Encountered";
    mysqli_close($con);
?> 

2 个答案:

答案 0 :(得分:3)

我认为最好和最短的方法是使用单个文件add_article.php

<?php

if(!empty($_POST['title'])){

    $con=mysqli_connect("localhost","root","","bookdb");

    if (!$con){
        die ("Failed to connect to MySQL: " . mysqli_connect_error($con));
    }
    $sql = "INSERT INTO article (title, author, description,location)
    VALUES('$_POST[title]','$_POST[author]','$_POST[description]','$_POST[location]')";

    if(mysqli_query($con,$sql))
        echo "Article inserted";
    else
        echo "An Error was Encountered";
    mysqli_close($con);

}
?>
<form id="form" action="add_article.php" method="post">
    <div class="span4">
        <div class="control-group">
            <input type="text" placeholder="title" name="title"><br/><br/>
            <input type="text" placeholder="author" name="author"><br/><br/>
            <textarea placeholder="article summary" rows="12" maxlength="300" name="description"></textarea><br/><br/>
            <input type="text" placeholder="location e.g. lubaga cathedral" name="location"><br/><br/>
        </div>
</form>

答案 1 :(得分:1)

你可以做@relentless说的话:

if(article is inserted)
{
echo header('location:www.example.com');
}

或使用元刷新:

if(article is inserted)
{
echo '<meta http-equiv="refresh" content="0;URL="www.example.com" />';
}    

如果出现错误,您可以使用上述内容重定向到错误页面,或仅使用else {}来显示错误消息:

else
{
 //redirect
 echo '<meta http-equiv="refresh" content="0;URL="www.example.com/errorpage" />';
//or
echo 'Error: '.mysqli_error($con);
}

http://www.w3schools.com/php/func_mysqli_error.asp