PHP:留言读写功能实现

一、留言并保存

1、submitMsg.html :

<html>
<head>
    <meta charset="utf-8">
    <title>PHP留言读写功能实现</title>
</head>
<body>

<form action="write.php" method="POST">
    留言标题: <input type="text" name="title">
    <br/>
    留言内容: <input type="text" name="content">
    <br/>
    <input type="submit" value="提交">
</form>

</body>
</html>

效果图:

这里写图片描述

2、write.php

<?php
$str = $_POST["title"] . "," . $_POST["content"] . "\n";
//以逗号连接标题和内容,方便数组的创建
//每写入一次留言,换行

$file = fopen("msg.txt", "a");//打开文件,获取资源类型的变量(管道)

fwrite($file, $str);//(沿着管道)写入文件

fclose($file);//关闭资源(管道)

echo "ok";
?>

点击提交后,写入文件。并提示提交成功:OK

效果如图:

这里写图片描述

记事本:

这里写图片描述

二、读取留言:

1、readMainMsg.php

<?php
$file = fopen("msg.txt", "r");//打开文件,获取资源类型的变量(管道)

$i = 1;
while (($rowContent = fgetcsv($file)) != false) {
    echo '<li><a href="readDetailMsg.php?id=', $i, '" >', $rowContent[0], "</li>";
    $i++;
}

fclose($file);//关闭资源(管道)
?>

效果如图:

这里写图片描述

2、readDetailMsg.php

<?php
$id = $_GET["id"];//获取指定内容id

$file = fopen("msg.txt", "r");//打开文件,获取资源类型的变量(管道)

$rowId = 1;
while (($rowContent = fgetcsv($file)) != false) {//无内容:输出FALSE,有内容:输出内容
    if ($rowId == $id) {
        //print_r($rowContent);//输出数组
        echo '<h1>标题:', $rowContent[0], '</h1>';
        echo '<p>内容:', $rowContent[1], '</p>';
    }
    $rowId++;
}

fclose($file);//关闭资源(管道)
?>

效果如图:

这里写图片描述

参考:PHP3小时光速入门:记事本

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值