好的,我有这段代码:
<?php
//this is the thispage.php
$file = "data.txt";
$name = $_POST['name'];
$url = $_POST['url'];
$data = file('data.txt');
$i = 1;
foreach ($data as $line) {
$line = explode('|', $line);
$i++;
}
if (isset($_POST['submits'])) {
$fp = fopen($file, "a+");
fwrite($fp, $i."|".$name."|".$url."|'n");
fclose($fp);
}
?>
和这个指数.php。
<html>
<head>
</head>
<body>
<br>
<form name="form1" action="thispage.php" method="POST">
<input type="text" name="name">
<input type="text" name="url">
<input type="submit" name="submits" value="ADD"><br>
</form>
<form name="form2" action="thispage.php" method="POST">
<?php
$display = file("data.txt");
for ($i=0; $i<=count($display)-1; $i++) {
$lines = explode("|",$display[$i]);
print('<input type="hidden" name="id" value="'.$lines[0].'">
<input type="text" name="name" value="'.$lines[1].'">
<input type="text" name="url" value="'.$lines[2].'">
<input type="submit" name="update" value="UPDATE">
<input type="submit" name="delete" value="DELETE"><br>');
}
?>
</form>
</body>
</html>
这就是.txt包含的数据。
1|John|http://www.john.com|
2|Mark|http://www.mark.com|
3|Fred|http://www.fred.com|
4|Johnxxx|asdasdasdasd|
我很难过,让这个工作,尝试更新和删除,我可以添加,但我也无法更新和删除。 希望你们能帮助我,这是过期。 提前谢谢你。
我不太确定你在这里要求什么,通常你会像ulvund所说的那样使用数据库进行这种存储,但正如你所说,这是一个实验,所以我接受它;)
根据您提供的代码,即插入和查看,我看到可能会出现一些问题。您说的更新和删除问题,但是该部分没有代码。您有一些代码无法正常工作,或者您正在询问下一步该怎么做?
我看到的这段代码的问题
-
如果有人提交带有"'"(换行符(的表单,该怎么办?这会弄乱您的数据(或至少几行,具体取决于用户发布的'数量。
-
当您删除第 #2 行并再次插入新行时会发生什么?您最终会得到 2 行 #4,因为您计算行数的方式并使用该结果来构成下一个 INSERT 的 id
-
$line = 爆炸('|', $line(;"thispage.php"中的这一行什么都不做,因为你只想计算行数,而不是将所有数据提取到数组中。正如我之前所说,这种编造 id 的方式不是一个好主意。
因此,如果这个实验值得你付出努力,你需要考虑将"自动增加ID"存储在一个单独的文件中,或者将数据库文件的第一行变成元行,包含元数据作为AI和你可能想要的其他东西。
根据您所拥有的内容,如下所示的内容可能会起作用。但是,请务必阅读 user1362861 和 ulvund 的答案。有很多方法可能会出错,如果您打算在实践中应用它,最好使用数据库。
<?php
//this is the thispage.php
$file = "data.txt";
$name = $_POST['name'];
$url = $_POST['url'];
$id = $_POST['id'];
$mode = $_POST['mode'];
$data = file('data.txt');
$i = 1;
foreach ($data as $line) {
// You're not doing anything with this.
//$line = explode('|', $line);
$i++;
}
if (isset($_POST['submits'])) {
if ($mode === 'add') {
$fp = fopen($file, "a+");
fwrite($fp, $i."|".$name."|".$url."|'n");
fclose($fp);
} else {
$fp = fopen($file, "r+");
foreach ($data as $line) {
$l = explode('|', $line); // $l = substr($line, 0, strpos($line, '|'));
if ($id === $l[0]) {
if ($mode === 'update') {
fwrite($fp, $l[0]."|".$name."|".$url."|'n");
} // else delete; don't re-write this line.
} else {
fwrite($fp, $line);
// This assumes IDs are attached to data, not line numbers.
// If that isn't the case, storing the ID (line number) is pointless.
}
}
fclose($fp);
}
}
?>
为什么不使用数据库呢? 您可以使用数据库轻松更新,删除,插入。