论坛发帖或写邮件时,编辑器都会某个时间间隔内自动保存我们的数据,本章PHP教程,UncleToo给大家分享利用PHP+JQuery实现自动保存数据的实例。
创建表:
~~~
Create TABLE tbl_cms (
id int(11) NOT NULL AUTO_INCREMENT,
header varchar(255) DEFAULT NULL,
content text,
date_created datetime DEFAULT NULL,
date_last_modified datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
~~~
CSS样式代码:
~~~
<style>
textarea{
width: 878px;
height: 310px;
border: 3px solid #cccccc;
padding: 5px;
font-family: Tahoma, sans-serif;
}
#timer{
width:400px;
float:left;
}
#upd_div{
float:left;
color:red;
}
</style>
~~~
Javascript代码:
~~~
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
timePicker(10);
});
</script>
<script>
// timer code starts here ---
//var init2 = 50;
var s;
function timePicker(vr) {
if (vr > 0)
{
if (vr > 1) {
$('#timer').html('数据将在 '+ vr+' 秒后自动保存!');
} else {
$('#timer').html('数据将在 1 秒后自动保存!');
}
vr--;
s = setTimeout('timePicker(' + vr + ')', 1000);
} else {
clearInterval(s);
$.post('data.php',{txt_area:$('#dstr').val()},function(r){
$('#upd_div').html("Last Updated: "+r);
$('#timer').html('保存...数据将在 10 秒后自动保存!');
s = setTimeout('timePicker(' + 10 + ')', 5000);
return false;
});
}
}
</script>
~~~
HTML代码:
~~~
<div class="content">
<div class="heading">
php实现在特定时间间隔自动保存数据
</div>
<div id='dv1'>
输入内容:
<textarea id="dstr"></textarea>
<div id="timer_upd_dev"><div id="timer">X 秒 </div><div id="upd_div"> </div></div>
</div>
</div>
~~~
PHP代码:
~~~
<?php
$con=mysqli_connect("localhost","root","","a");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['txt_area']) && $_POST['txt_area'] != '') {
$data = mysql_real_escape_string($_POST['txt_area']);
$qry = "Select count(*) as cnt from tbl_cms";
$res = mysqli_query($con,$qry);
$row = mysqli_fetch_array($res);
$date_last_modified = date('Y-m-d H:i:s');
if ($row['cnt'] == 0) {
$qry_ins = "Insert INTO `tbl_cms` (`id`, `header`, `content`, `date_created`, `date_last_modified` )
VALUES
('1', 'About Us', '" . $data . "', '" . date('Y-m-d H:i:s') . "', '" . $date_last_modified . "' );";
mysqli_query($con,$qry_ins);
} else {
$qry_upd = "Update `tbl_cms` set `content`='" . $data . "', `date_last_modified` ='" . $date_last_modified . "' where id=1";
mysqli_query($con,$qry_upd);
}
echo $date_last_modified;
}
?>
~~~