After inserting data into MySQL, i get redirected to the PHP file. not cool! How do i display error or success messages in the same HTML file.
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);
?>
I think the best and shortest way is to work with a single file, 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>
You can either do what @relentless said:
if(article is inserted)
{
echo header('location:www.example.com');
}
Or using meta refresh:
if(article is inserted)
{
echo '<meta http-equiv="refresh" content="0;URL="www.example.com" />';
}
On error you use the above to redirect to an error page, or merely use else{} to display an error message:
else
{
//redirect
echo '<meta http-equiv="refresh" content="0;URL="www.example.com/errorpage" />';
//or
echo 'Error: '.mysqli_error($con);
}