1.6留言板作业 为什么我一修改,其他的数据就被删除了,只保留了我当前修改的这条数据

来源:1-6 作业题

一种相思花自飘零水自流

2019-05-12 21:17:59

<?php
header('content-type:text/html;charset=utf-8');
date_default_timezone_set('PRC');
$file = 'msg.txt';
$msgs=[];
if(file_exists($file))//检测文件是否存在
{//读取文件中的内容
$string=file_get_contents($file);
if(strlen($string)>0)//有内容
{
$masg=unserialize($string);//反序列化
}
}
$editkey=$_GET['id'];
$editmsgs=$masg[$editkey];
//检测用户是否点击了提交按钮
if(isset($_POST['pubMsg']))
{
$editmsgs['username']=$_POST['username'];
$editmsgs['title']=strip_tags($_POST['title']);
$editmsgs['content']=$_POST['content'];
//原值传入数组

   //将指定位置的数据修改为接收到的新数据。
$msgs[$editkey]=$editmsgs;
//将所有数据序列化
$msgs=serialize($msgs);
if(file_put_contents($file,$msgs))//向指定文件写内容成功
{
echo "<script>alert('修改成功!');location.href='/text/index.php';</script>";
}
else{
echo "<script>alert('修改失败!');location.href='/text/index.php';</script>";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
   <script type="text/javascript" src="http://www.francescomalagrino.com/BootstrapPageGenerator/3/js/jquery-2.0.0.min.js"></script>
   <script type="text/javascript" src="http://www.francescomalagrino.com/BootstrapPageGenerator/3/js/jquery-ui"></script>
   <link href="http://www.francescomalagrino.com/BootstrapPageGenerator/3/css/bootstrap-combined.min.css" rel="stylesheet" media="screen">
   <script type="text/javascript" src="http://www.francescomalagrino.com/BootstrapPageGenerator/3/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
   <div class="row-fluid">
       <div class="span12">
           <div class="page-header">
               <h1>
IMOOC留言板-<span>V1.0</span>
               </h1>
           </div>
           <div class="hero-unit">
               <h1>
修改
               </h1>
           </div>
           <form action="#" method="post">
               <fieldset>
                   <legend>请留言</legend>
                   <label>用户名</label><input style="width:100%;" value="<?php echo $editmsgs['username']?>" type="text" name="username" required />
                   <label>标题</label><input style="width:100%;"  value="<?php echo $editmsgs['title']?>"  type="text" name="title" required />
                   <label>内容</label><textarea style="width:100%;"  name="content" rows="5" cols="30" required><?php echo $editmsgs['content']?></textarea>
                   <hr>
                   <input type="submit" class="btn btn-primary btn-lg" name="pubMsg" value="发布留言"/>
                   <a href="/text/index.php"  class="btn btn-primary btn-lg">查看留言</a>
               </fieldset>
           </form>
       </div>
   </div>
</div>
</body>
</html>

写回答

1回答

好帮手慕小尤

2019-05-13

同学你好,在反序列化时使用的数组与提前定义的数组不是同一个数组,导致在修改留言时,重新序列化并没有在原先的序列化上进行修改,所以造成其他数据被删除。

http://img.mukewang.com/climg/5cd907fd0001282107230333.jpg

祝学习愉快!

0

0 学习 · 4928 问题

查看课程