您的位置:首页 > 编程语言 > PHP开发

妙味课堂中使用php,MySQL,ajax制作简易的新浪微博页面

2016-09-05 10:35 495 查看
将简易的新浪微博分为三个部分:sina.html用于显示页面

      sina_post.php作为ajax的请求页面

              sina.sql用来在数据库中建立表messages

其中sina.sql的内容如下:

CREATE TABLE  messages(

    ID int NOT NULL AUTO_INCREMENT PRIMARY KEY,

    content varchar(170) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,

    posttime INT NOT NULL

    );

即可在sina数据库中创建一个名为messages的表,它包含三列,即id,content,posttime.其中id为自增的。

sina.html代码如下

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
*{margin:0;padding:0;}
#ul1{width:300px;height:300px;overflow:hidden;border:1px solid black;
margin:10px auto;}
#ul1 li{list-style:none;padding:2px;border-bottom:1px solid #999;}
</style>
<title>无标题文档</title>
<script type="text/javascript" src="ajax.js"></script>
<script>
window.onload=function()<!-- -->
{
var oTxt=document.getElementById("txt1");
var oBtn=document.getElementById("btn1");
var oUl=document.getElementById("ul1");

oBtn.onclick=function()
{
var url='sina_post.php?act=add&content='+oTxt.value;
var oAjax=InitAjax();
DoAjaxGet(oAjax,url,function(str){
});
oTxt.value="";
}
}
</script>
</head>

<body>
<textarea id="txt1" rows="10" cols="40"></textarea>
<input id="btn1" type="button" value="发布"/>
<ul id="ul1">
</ul>
</body>
</html>

最为重要的是sina_post.php,它接收ajax发送过来的数据,并将其添加到数据库中

其代码应为:

<?php

switch($_GET['act'])

{
case 'add':

mysql_connect('localhost','root','');
mysql_select_db("sina");
$content=$_GET['content'];
$t=time();
$sql="INSERT INTO messages (content,posttime) VALUES('{$content}',{$t})";
mysql_query($sql);//问题在于id的取值中。不能实现自增
break;

}

?>

对于上述代码中的红色部分,应该要注意,在妙味的视频教程中使用的是

$sql="INSERT INTO messages (ID,content,posttime) VALUES(0,'{$content}',{$t})";

这是不正确的,因为首先id已经定义为自增了。现在每点击一次就添加,到id=0的地方,数据库是不显示的。

所以应该将,ID去掉,只插入Content,posttime,数据库中的id会自增。这样就能插入到数据库中
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: