下面为您介绍的是php开发中mysql表单提交防止重复刷新的实现方法,如果您之前遇到过类似的问题,不妨一看。
数据库为jokes,表为jokes,添加一个笑话为例
mysql表单提交页面:
<HTML>
<HEAD>
<TITLE> Our List of Jokes </TITLE>
</HEAD>
<BODY>
<?php
session_start(); // 启用session
$timetime = time();
$key ="sess_" . $time; // 根据时间生成一个随机的session key
$_SESSION[$key] = $time; // 设置session的值
?>
<FORM ACTION="input.php?tjid=1" METHOD=POST>
<P>Type your joke here:<BR>
<TEXTAREA NAME="joketext" ROWS=10 COLS=40 WRAP></TEXTAREA><BR>
//通过隐藏表单将 session 的 key传递到服务端处理
<input type="hidden" name="session_key" value="<?php echo $key;?>" />
<INPUT TYPE=SUBMIT NAME="submitjoke" VALUE="SUBMIT">
</FORM>
</BODY>
</HTML>
处理页面:
<HTML>
<HEAD>
<TITLE> Our List of Jokes </TITLE>
</HEAD>
<BODY>
//连接数据库:
<?php
$dbcnx =mysql_connect("localhost","root","******");
if (!$dbcnx) {
echo( "<P>Unable to connect to the " .
"database server at this time.</P>" );
exit();
}
// Select the jokes database
if (! @mysql_select_db("jokes") ) {
echo( "<P>Unable to locate the joke " .
"database at this time.</P>" );
exit();
}
//启动session:
session_start();
$key = $_POST['session_key'];
if(!$key || $_SESSION[$key] != substr($key, 5)){
// 如果没有传 session_key 参数
// 或者 session_key 参数值截断 sess_后的数字 与 session参数值不匹配
unset($_SESSION[$key]); // 删除 session 值
echo "chu cuo la";// 然后考虑是否要提示错误,或者转入另一个页面
exit(); // 终止页面代码执行
}
// 下面进行数据写操作
if ("SUBMIT" ==$_POST["submitjoke"] ) {
$sql="INSERT INTO Jokes (joketext)
VALUES ('$_POST[joketext]')
";
if (mysql_query($sql)) {
echo("<P>Your joke has been added.</P>");
} else {
echo("<P>Error adding submitted joke: " .
mysql_error() . "</P>");
}
// 数据操作完成后,删除session
unset($_SESSION[$key]);
}
?>
//显示笑话内容:
<P> Here are all the jokes in our database: </P>
<BLOCKQUOTE>
<?php
$result = mysql_query(
"SELECT * FROM Jokes");
if (!$result) {
echo("<P>Error performing query: " .
mysql_error() . "</P>");
exit();
}
// Display the text of each joke in a paragraph
while ( $row = mysql_fetch_array($result) ) {
echo("<P>" . $row["JokeText"] . "</P>");
}
?>
</BODY>
</HTML>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.
- 91.
【编辑推荐】