我有这个代码用于发布表单的方法。
的config.php
<?php
include('db.php');
function string_limit_words($string, $word_limit) {
$words = explode(' ', $string);
return implode(' ', array_slice($words, 0, $word_limit));
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$title=mysql_real_escape_string($_POST['title']);
$body=mysql_real_escape_string($_POST['body']);
$title=htmlentities($title);
$body=htmlentities($body);
$newtitle=string_limit_words($title, 6);
$urltitle=preg_replace('/[^a-z0-9]/i',' ', $newtitle);
$newurltitle=str_replace(" ","-",$newtitle);
$date=date("Y/m/d");
$url=$date.'/'.$newurltitle.'.html';
mysql_query("insert into blog(title,body,url) values('$title','$body','$url')");
}
?>
使用上面的代码,我成功发布了表单,我可以找到该文件。但是,在发布表单后,config.php只留空。我想要的是重定向到另一个页面,如congratz.html页面。
congratz.html
<body>
<h2>CONGRATZ, YoOU HAVE SUCCESSFULLY POST THE FORM TO THE DATABASE</h2>
</body>
我所知道的是要添加标题行,如:
header( 'Location: http://www.example.com/congratz.html');
在config.php中。
但是我不知道如何做到这一点或将标头放在config.php中的哪个位置。
我只是在学习php和自学成才。请帮忙。谢谢。
答案 0 :(得分:1)
在查询后添加此内容
if(mysql_affected_rows()>0)//checking weather the query worked or not
{
header( 'Location: http://www.example.com/congratz.html');
}
所以你的整个代码应该是这样的
<?php
include('db.php');
function string_limit_words($string, $word_limit) {
$words = explode(' ', $string);
return implode(' ', array_slice($words, 0, $word_limit));
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$title=mysql_real_escape_string($_POST['title']);
$body=mysql_real_escape_string($_POST['body']);
$title=htmlentities($title);
$body=htmlentities($body);
$newtitle=string_limit_words($title, 6);
$urltitle=preg_replace('/[^a-z0-9]/i',' ', $newtitle);
$newurltitle=str_replace(" ","-",$newtitle);
$date=date("Y/m/d");
$url=$date.'/'.$newurltitle.'.html';
mysql_query("insert into blog(title,body,url) values('$title','$body','$url')");
if(mysql_affected_rows()>0)//Checking weather the query worked or not
{
header( 'Location: http://www.example.com/congratz.html');
}
}
?>
此外,mysql已被弃用,学习mysqli或PDO
对于mysqli函数,请检查此链接http://php.net/manual/en/book.mysqli.php
对于PDO功能,请检查此链接http://php.net/manual/en/book.pdo.php
要了解标题,请查看此链接http://php.net/manual/en/function.header.php
答案 1 :(得分:0)
只需在查询后放置标题。
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$title=mysql_real_escape_string($_POST['title']);
$body=mysql_real_escape_string($_POST['body']);
$title=htmlentities($title);
$body=htmlentities($body);
$newtitle=string_limit_words($title, 6);
$urltitle=preg_replace('/[^a-z0-9]/i',' ', $newtitle);
$newurltitle=str_replace(" ","-",$newtitle);
$date=date("Y/m/d");
$url=$date.'/'.$newurltitle.'.html';
mysql_query("insert into blog(title,body,url) values('$title','$body','$url')");
header( 'Location: http://www.example.com/congratz.html');
}