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

PHP 新闻列表实例(数据库读取 删除数据,页面跳转)

2017-11-29 19:08 871 查看
conn.php  连接数据库的页面

index.php  主页,显示所有新闻列表

del.php   删除新闻的页面,删除后自动跳转到主页。

1、conn.php  连接数据库页面

<?php
//声明PHP输出数据的字符集
header("content-type:text/html;charset=utf-8");
//(0)数据库配置信息
$db_host	= "localhost:3306";
$db_user	= "root";
$db_pwd		= "root";
$db_name	= "007online";
//(1)PHP连接MySQL服务器
$link = @mysql_connect($db_host,$db_user,$db_pwd);
if(!$link)
{
echo "<font size=7 color=red>PHP连接MySQL失败!</font>";
exit();
}
//(2)选择当前数据库
if(!mysql_select_db($db_name))
{
echo "<font size=7 color=red>选择数据库{$db_name}失败!</font>";
exit();
}
//(3)设置MySQL返回的数据字符集
mysql_query("set names utf8");

?>
2、index.php  主页,显示所有新闻列表
<?php
include "conn.php";

//(4)执行SQL语句
$sql = "select * from 007_news ";
$result = mysql_query($sql,$link);
if(!$result)
{
echo "<font size=7 color=red>数据查询失败!</font>";
exit();
}

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE>新闻列表 </TITLE>
</HEAD>
<script type="text/javascript">
function confirmDel(id)
{
if(window.confirm("你确定要删除吗?"))
{
location.href="del.php?id="+id;
}
}

</script>
<BODY>
<table width="100%" border="1 solid" rules="all" align="center" cellpadding="5">
<tr bgColor="#e0e0e0">
<th>编号</th>
<th>新闻标题</th>
<th>作者</th>
<th>来源</th>
<th>排序</th>
<th>点击率</th>
<th>发布时间</th>
<th>操作</th>
</tr>

<?php
date_default_timezone_set('PRC');   //设置中国时区
$str="";
$n=1;
while($arr=mysql_fetch_assoc($result))  //每读出一条数据就加一行<tr>
{
if($n%2==0)
{
$str.="<tr align='center' bgColor='#f6f6f6'>";
}
else
{
$str.="<tr align='center'>";
}
$str.="<td>".$arr['id']."</td>";
$str.="<td>".$arr['title']."</td>";
$str.="<td>".$arr['author']."</td>";
$str.="<td>".$arr['source']."</td>";
$str.="<td>".$arr['orderby']."</td>";
$str.="<td>".$arr['hits']."</td>";
//$str.="<td>".$arr['addate']."</td>";
$str.="<td>".date("Y-m-d H:i",$arr['addate'])."</td>";
$str.="<td><a href='javascript:void(0)'>修改</a>/<a href='javascript:void(0)' onClick='confirmDel(".$arr['id'].")'>删除</a></td>";

$str.="</tr>";

$n++;
}
echo $str;
?>

</table>

</BODY>
</HTML> 
3、del.php   删除新闻的页面,删除后自动跳转到主页。
<?php
include "conn.php";

$id=(int)$_GET["id"];
$sql="delete from 007_news where id=".$id;

if(mysql_query($sql))
{
echo "<script>location.href='index.php'</script>";
}
else
{
echo "删除失败!";
}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php
相关文章推荐