1

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

索引.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);
?> 
4

2 回答 2

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>
于 2013-09-25T23:26:42.173 回答
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

于 2013-09-25T23:32:32.450 回答