风之旅人 Android Dev Engineer

12.新闻管理项目

2019-10-24
PHP

新闻管理项目

bilibili👉 https://www.bilibili.com/video/av15525720/?p=26
项目源码 👉 PHP新闻管理项目源码.zip

整体流程

  • 添加新闻表单
    1. 接收数据
    2. 数据验证:合法性验证。标题不能为空,内容不能为空
    3. 提示用户,同时让用户重新再来(回到新增表单页面)
    4. 数据入库

公共文件

//1. 中文处理
header('Content-type:text/html;charset=utf-8');
//连接认证:本地 & 阿里云
$conn=mysqli_connect('127.0.0.1:3306','root','123456') or die("连接失败 ".mysqli_connect_error());

//封装MySQL语法错误检查函数并执行
/*
 * @param $link  数据库连接对象
 * @param string $sql,要执行的SQL指令
 * @return $res,正确执行完返回的结果,如果SQL错误,直接终止
*/
function execSQL($link,$sql){
  //执行SQL
  $res = mysqli_query($link,$sql);

  //处理可能存在的错误
  if(!$res){
    echo 'SQL执行错误,错误编号为:' . mysqli_errno($link) . '<br/>';
    echo 'SQL执行错误,错误信息为:' . mysqli_error($link) . '<br/>';

    //终止错误继续执行
    exit;
  }

  //返回结果
  return $res;
}

//字符集处理
execSQL($conn,'set names utf8');
//选择数据库
execSQL($conn,'use News');
//mysqli_close($conn);

添加内容

header('Content-type:text/html;charset=utf-8');
echo '<pre>';

//1. 接收数据
//接受用户提交数据
var_dump($_POST);

$title=isset($_POST['title'])?trim($_POST['title']):'';		//title 是字符串(重要)
$isTop=isset($_POST['isTop'])?(integer)$_POST['isTop']:2;	//数字需求,而且不重要
$publisher=isset($_POST['publisher'])?trim($_POST['publisher']):'佚名';
$content=isset($_POST['content'])?trim($_POST['content']):'';//trim通常针对字符串
//echo $title;

//2. 数据验证:合法性验证。标题不能为空,内容不能为空
//3. 提示用户,同时让用户重新再来(回到新增表单页面)
if(empty($title)||empty($content)){
  //提示同时回到提交页
  //🐖 header 之前不能有 echo 等输出,但不会影响后面的代码执行
  //🐖 url 开发中应使用绝对路径
  header('Refresh:3;url=news_add.html');	//header前不能有输出,header:refresh不会阻止脚本执行

  //标题和内容至少有一个为空
  //echo '标题和内容都不能为空!';

  //阻止脚本继续执行
  exit('标题和内容都不能为空!');
}

//4. 数据入库
include_once 'my_public.php';

$time=time();
$sql="insert into n_news values(null,'{$title}',$isTop,'{$content}','{$publisher}',$time)";

$insert_id = execSQL($conn,$sql);

//4. 提示用户操作结果,并跳转到列表页(跳转到详情页)
//成功操作,提示同时去到列表页
header('Refresh:3;url=my_news.php');
echo $title . ' 增加成功!';

新闻列表

//1. 获取所有新闻内容并显示
//操作数据库获取数据
include_once 'my_public.php';
//组织SQL获取所有新闻信息
$sql = "select * from n_news";
//执行
$res = execSQL($conn,$sql);				//拿到结果集


//2. 从结果集中取出所有的记录:一次取一条,一条一个数组;然后将所有的记录放到一个数组中:形成一个典型的二维数组
//循环遍历所有结果
$news = array();							//保存取出的记录(数组)

//方案1:获取结果集中记录数,然后for循环
//🐖 mysqli_num_fields 会造成指针下移,导致只能取出一半的结果
/*$num = mysqli_num_fields($res);
echo $num.'<br>';
for($i = 0;$i < $num;$i++){
  //🐖 $news[] 自增
  $news[] = mysqli_fetch_assoc($res);
}
*/

//方案2:利用while循环,每次取到数据之后判断保存数据的结果,只要结果不为false,那么一直取
while($row = mysqli_fetch_assoc($res)){
  $news[] = $row;
}
//echo '<pre>';
//print_r($news);

//3. 一个已经做好的HTML模板能够显示数据:前端
//包含显示模板(HTML)
include_once 'news.html';

//4. PHP想办法将数据在HTML中显示(二者结合):PHP包含HTML
//修改 news.html

用于显示的 news.html

<?php foreach($news as $k => $new):?>
  <tr>
    <td><?php echo $k + 1;?></td>
    <td><?php echo $new['title'];?></td>
    <td><?php echo date('Y年m月d日 H时i分s秒',$new['pub_time']);?></td>
    <td><?php echo $new['publiser']?></td>
    <td><?php echo $new['isTop'] == 1 ? '是' : '否';?></td>
    <td style="text-align:center;">
      <a href="news_edit.php?id=<?php echo $new['id'];?>">修改</a>&nbsp;|                
      <a href="news_delete.php?id=<?php echo $new['id'];?>" onclick="return confirm('是否确定删除当前新闻?');">删除</a>&nbsp;    
    </td>
  </tr>
<?php endforeach;?>

效果

注意细节:

  1. 数据的显示要通过循环遍历输出:需要明确PHP是如何保存数据
  2. 数据的格式需要按照需求来显示:列表、时间、是否置顶

删除新闻

删除按钮

<a href="my_delete.php?id=<?php echo $new['id'];?>" onclick="return confirm('是否确定删除当前新闻?');">删除</a>&nbsp;    
//新闻管理:删除指定新闻
header('Content-type:text/html;charset=utf-8');

//接收要删除的新闻ID
$id = isset($_GET['id']) ? (integer)$_GET['id'] : 0;	//0不会存在
if($id == 0) {
  header('Refresh:3;url=news.php');
  echo '当前要删除的新闻不存在!';
  exit;
}

//删除数据
include_once 'my_public.php';

//组织SQL并执行
execSQL($conn,'delete from n_news where id = ' . $id);

//删除后更新页面
//方案一
header('Refresh:0;url=my_news.php');
//echo '当前新闻删除成功!';

//方案二 🌈效果更好,页面不会重新刷新
/*
$res = execSQL($conn,"select * from n_news");				//拿到结果集
$news = array();
while($row = mysqli_fetch_assoc($res)){
  $news[] = $row;
}
include_once 'news.html';
*/

修改新闻

<!-- 🐖🐖别忘了传ID -->
<input type="hidden" name="id" value="<?php echo $update['id'];?>"/>
<!-- 单选 -->
<td width="10%">
  <input type="radio" name="isTop" <?php echo isset($update['isTop'])&&$update['isTop']==1?'checked="checked"':"";?> value="1"/>是
  <input type="radio" name="isTop" <?php echo isset($update['isTop'])&&$update['isTop']==0?'checked="checked"':"";?> value="0"/>否
</td>

找到指定id的对象,跳转到编辑页(edit.html)进行修改 , ==这里不能用 add.html 取代==

//新闻管理:修改指定新闻-找到指定id的对象,跳转到编辑页
//🐖编辑页不同于添加页面...不太灵活
header('Content-type:text/html;charset=utf-8');

$id=isset($_GET['id'])==true?$_GET['id']:-1;
if($id==-1){
	header('Refresh:3;url=my_news.php');
	echo '当前要修改的新闻不存在!';
	exit;
}

//获取当前ID对应的新闻信息
include_once 'my_public.php';
$res=execSQL($conn,"select * from n_news where id = ".$id);
$update= mysqli_fetch_assoc($res);

//print_r($update);
include_once 'news_edit.html';

mysqli_fetch_assoc() 从结果集中取出一行作为关联数组 👉 https://www.runoob.com/php/func-mysqli-fetch-assoc.html

写入数据库:

//新闻管理:修改指定新闻
header('Content-type:text/html;charset=utf-8');

//接收数据并验证
$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
$title = isset($_POST['title']) ? trim($_POST['title']) : '';	//title是字符串(重要)
$isTop = isset($_POST['isTop']) ? intval($_POST['isTop']) : 0 ;	//数字需求,而且不重要
$publiser = isset($_POST['publisher']) ? trim($_POST['publisher']) : '';
$content = isset($_POST['content']) ? trim($_POST['content']) : '';

//数据验证:标题和内容均不能为空
if(empty($title) || empty($content)){
  //提示同时回到提交页
  header('Refresh:3;url=my_news.php');	//header前不能有输出,header:refresh不会阻止脚本执行

  //标题和内容至少有一个为空//阻止脚本继续执行
  exit('标题和内容都不能为空!');
}

//组织SQL更新到数据库
include_once 'my_public.php';
$sql = "update n_news set title = '{$title}',isTop = {$isTop} ,publiser='{$publiser}' ,content='{$content}' where id = {$id}";
$res = execSQL($conn,$sql);

//提示成功
header('Refresh:0;url=my_news.php');
//echo '当前新闻更新成功!';

搜索新闻

//新闻管理:删除指定新闻
header('Content-type:text/html;charset=utf-8');


//获取关键字,进行模糊查询
$keywords=$_POST['title'];

include_once 'my_public.php';
//组织SQL并执行
$res=execSQL($conn,"select * from n_news where title like '%$keywords%' ");

$news=array();

while($row=mysqli_fetch_assoc($res)){
  $news[]= $row ;
}

include_once 'news.html';

新闻展示页(news.html):

<form class="form-inline definewidth m20" action="my_search.php" method="post">
    标题:<input name="title" class="abc input-default" value="<?php echo isset($keywords)?$keywords:"";?>"></input>&nbsp;&nbsp;
    <button type="submit" class="btn btn-primary" >查询</button>&nbsp;&nbsp;
    <!--
    <button type="button" class="btn btn-primary" onclick="location='news_add.html'">添加</button>&nbsp;&nbsp;
    -->
    <button type="button" class="btn btn-primary" onclick="javascript:window.open('news_add.html')">添加</button>&nbsp;&nbsp;
</form>


相关文章

评论