PHP简单新闻发布系统

01月 11, 2010 by admin
Filed under: PHP教程 

前天写的一个比较简单的PHP新闻发布系统,不知道有没有什么地方写得不太科学的,欢迎提意见

1、连接数据库
$conn=mysql_pconnect (“localhost”, “root”, “”);
mysql_select_db(“news”,$conn); //可以不用来选择数据库,在每查询一次只要把链接变量加上去就可以了,这样的话,方便以后对查询模式更改数据库

2、添加\修改新闻
require_once(“conn.php”); //引用数据库连接页面
if (@$_POST["submit"]) { //判断表单提交,提交按钮名称submit,_POST为提取表单数据,_GET提取参数
$title=$_POST["title"];
$from=$_POST["from"];
$content=$_POST["content"];
$id=$_POST["id"];
$datetime=date(“y/m/d”); //PHP的时间函数,比ASP方便多了呵
if ($id!=”") {//!empty($id) 判断ID 不等于空或者不等于0的时候   $exec不用写的
mysql_query($exec=”update news set title=’”.$title.”‘,aaa=’”.$from.”‘,content=’”.$content.”‘ where id=”.$id.”"); //SQL语句,更新表
echo “<script>alert(‘修改成功!’);self.location=’index.php’;</script>”;
}
else {
mysql_query(“INSERT INTO news(title,aaa,content,datetime) VALUES(‘”.$title.”‘,’”.$from.”‘,’”.$content.”‘,’”.$datetime.”‘)”); //SQL插入记录
echo “<script>alert(‘添加成功!’);self.location=’add.php’</script>”;
}
}

表单部分:
if ($_GET["action"]==”edit”) {//你都已经用POST提交了,为什么还用GET接收呢,直接$action就可以啊(朋友的注释,不过我这个action的值是从另外一个页面提交过来的,貌似应该用GET)
  
$exec=”select * from news where id=”.$_GET["id"].”";
$result = mysql_query($exec);
$rs=mysql_fetch_object($result);
$title=$rs->title;
$from=$rs->aaa;
$content=$rs->content;
$id=$rs->id;
}
<form name=”form1″ method=”post” action=”add.php” onsubmit=”return ture()”>
<input type=”text” name=”title” value=”<?php echo $title; ?>” />
<input type=”text” name=”from” value=”<?php echo $from; ?>” />
<textarea name=”content” cols=”45″ rows=”5″><?php echo $content; ?></textarea>
<input type=”hidden” name=”id” value=”<?php echo $id; ?>” />
<input type=”submit” name=”submit” value=”提交” />
</form>

3、新闻列表及删除

<?php
require_once(“conn.php”); //执行删除新闻
$action=$_GET["action"];
if (!empty($action)) {//用函数判断 如果action不等于的时候就执行
mysql_query($exec=”delete from news where id=”.$_GET["id"].”");
//mysql_query(“delete from news where id=”.$_GET["id"].”");
echo “<script>alert(‘删除成功!’);self.location=’index.php’;</script>”;
}
?>

$exec=”select id,title,aaa,datetime from news order by id desc”;
$result = mysql_query($exec);
//查询代码可以这样写 $result=mysql_query(“SELECT 字段名,id FROM `news` ORDER BY ID DESC”); 尽量不要用* 如果直接写字段名速度会更快
while($rs=mysql_fetch_object($result))//用对象的方式不如用数组的方式mysql_fetch_array
{
echo “<table width=’100%’ border=0 cellspacing=0 cellpadding=0 height=30><tr>”;
echo “<td width=’50%’>”.$rs->title.”</td>”;
echo “<td width=’20%’>”.$rs->datetime.”</td>”;
echo “<td width=’20%’>”.$rs->aaa.”</td>”;
echo “<td width=’10%’><a href=add.php?action=edit&id=”.$rs->id.”>修改</a> | <a href=?action=del&id=”.$rs->id.”>删除</a></td>”;
echo “</tr></table>”;
}

如果有和我一样PHP的初学者看到这篇文章的话,不建议你们直接复制代码就用,弄懂原理才是最重要的,呵呵。

Comments

Tell me what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!






վ״ Ϻϴ˾ ʽ ţƤѢƷ Ϻκբз ɰ LI Uϲ LI Uϲ 紫Ⱦ мƫ ޹˾ ֬Ƥ м֢״ 沿 ϴ 򲡳ʲô ﲡҽԺ ŷŵ LI Uϲͼ ǰ ҹ˾ ʪԹؽ׵֢״ °˾ QIE ˰ ᳡˾绰 LI Uϲʿ LI Uϲʹ˾ ֢֢״ LI Uϲʿ ֶҹ˾ и ţƤѢƷ ţƤѢͼƬ ﲡҽԺ