2014-10-10 107 views
0

我正在尝试使用php做一个讨论区。通过代码,所有用户名,数据&时间和注释都存储在代码中指定的data.txt文件中;但是,我无法获取data.txt中的内容以显示在页面上。我想我可能会让echo()部分的代码错误或者分隔符被搞砸了。php讨论区没有发表评论

<?php 
    $filename = "users.txt"; 
    $delim="*@*"; 

if (isset($_POST['submit'])){ 
    if (!($fp = fopen($filename, 'a+'))) { 
     echo("Error: Could not open $filename for writing."); 
} 
    else{ 
     $thePost=$_POST['post']; 
     $username=$_POST['uname']; 
     date_default_timezone_set('America/New_York'); 
     $string=(date('c')."\n".$username."\n".$thePost."\n*@*"); 
     fwrite($fp, $string); 
     $accounts = explode("\n", $theData); 
     fclose($fp); 
    } 
} 

    ?> 



<html> 
    <body> 
<h1> Discuss </h1> </br> </br> 

<form method="post" action="discussion.php"> 
    Name: <input name="uname" type="text" /> </br> 
    <textarea name="post" rows=4 cols=60>Add comment</textarea><br/> 
    <input type="submit" name="submit" value="Post Comment"/> 
</form> 
<?php 

if (!($fp = fopen($filename, 'a+'))) { 
     echo("Error: Could not open $filename for writing."); 
} 
    else{ 
     fread($fp, filesize($filename)); 
     $accounts = explode("*@*", $theData); 
     fclose($fp); 
     for ($i = 0; $i <count($accounts); $i++){ 
       echo($i); 
       echo($accounts[$i]); 
      } 
    } 
    ?> 
    </body> 
</html> 

我不确定我在做什么错误/为什么用户/数据/时间/评论不会在页面上发布任何内容。谢谢!

+0

你可以发布data.txt内容的示例吗? – slapyo 2014-10-10 18:24:36

+0

@slapyo 2014-10-11T15:30:33-04:00 bob 这是我的意见 * @ – alexdis 2014-10-11 19:31:24

+0

你只想要一行文件,或者你想单个作品(日期,名称,后)? – slapyo 2014-10-13 17:45:46

回答

0

这应该适合你。在末尾插入$string的额外换行符,否则下一行将追加到@的末尾。之后,在你的循环中换行。您可能遇到的问题是该帖子是否包含新行。您可能需要查看使用可能不会在帖子中发生的不同分隔符。把它放到数据库中可能会是一个好主意,尽管我不确定你到底在做什么。但是,这应该让你获得你正在寻找的信息。

<?php 
    $filename = "users.txt"; 
    $delim="*@*"; 

if (isset($_POST['submit'])){ 
    if (!($fp = fopen($filename, 'a+'))) { 
     echo("Error: Could not open $filename for writing."); 
} 
    else{ 
     $thePost=$_POST['post']; 
     $username=$_POST['uname']; 
     date_default_timezone_set('America/New_York'); 
     $string=(date('c')."\n".$username."\n".$thePost."\n*@*\n"); 
     fwrite($fp, $string); 
     $accounts = explode("\n", $theData); 
     fclose($fp); 
    } 
} 

    ?> 



<html> 
    <body> 
<h1> Discuss </h1> </br> </br> 

<form method="post" action="discussion.php"> 
    Name: <input name="uname" type="text" /> </br> 
    <textarea name="post" rows=4 cols=60>Add comment</textarea><br/> 
    <input type="submit" name="submit" value="Post Comment"/> 
</form> 
<?php 

if (!($fp = fopen($filename, 'a+'))) { 
     echo("Error: Could not open $filename for writing."); 
} 
    else{ 
     fread($fp, filesize($filename)); 
     $accounts = explode("*@*", $theData); 
     fclose($fp); 
     for ($i = 0; $i <count($accounts); $i++){ 
       $items = explode("\n", $accounts[$i]); 
       $date = $items[0]; 
       $user = $items[1]; 
       $post = $items[2]; 
      } 
    } 
    ?> 
    </body> 
</html>