php变量在脚本结束时变为空?

时间:2013-09-11 10:30:32

标签: php html

我有一个问题,我真的无法弄明白。基本上我在博客上工作,我有一个cookie的变量,返回一个帖子ID。问题是在脚本结束时,当我输入if(isset)语句时,变量似乎为null,我无法理解它背后的原因。它不会向数据库添加任何内容,也不会重定向到帖子ID。这是剧本:

<?php
//display the post
$post_id = $_GET['post_id'];
$query = mysql_query("SELECT * FROM posts WHERE `post_id`='". $post_id. "';") or die(mysql_error());
if(mysql_num_rows($query) != 0)
{
    $currentrow = mysql_fetch_array($query);
    echo $currentrow['title']. "<br>". $currentrow['text'];
}
else
{
    echo "that post does not exist.";
}
?>
</div>

<div id="comments">
<br>
<h3>Comments</h3>
<br>
<?php
//display the comments
$comments = mysql_query("SELECT * FROM `comments` JOIN `posts` ON(posts.post_id=comments.post_id) JOIN `users` ON(users.user_id=comments.user_id) WHERE posts.post_id=". "'". $_GET['post_id']. "'". ";")or die(mysql_error());;
while($currentRow = mysql_fetch_array($comments))
{
    echo $currentRow['ctext']. "<br>";
    echo "posted by <a href='/templates/profile.php?name=". $currentRow['name']. "'>". $currentRow['name']. "</a> at ". $currentRow['cdate']. " -- ". $currentRow['ctime']. "<br><br>";
}
?>
</div>

<Form Name ="submitform" Method ="POST" ACTION = "post.php">
<div id="commentbox">
<textarea name="textarea1" rows="10" cols="30">
<?php
echo $post_id;
?>
</textarea>
<br>
<input type="submit" name="submitcomment" value="Submit"><br>
</div>
</Form>
<?php
if(isset($_POST['submitcomment']))
{
    $comment = $_POST['textarea1'];
    $user_id = $_COOKIE['userid'];
    mysql_query("INSERT INTO comments(`ctext`, `cdate`, `ctime`, `user_id`, `post_id`) VALUES('$comment', 'CURDATE()', 'CURTIME()', '$user_id', '$post_id')") or die(mysql_error());
    header('Location: /post.php?post_id='. $post_id);
}
?>

</body>
</html>

正如您所看到的,我在if语句之前回显textarea1中的变量并返回正确的值,但最后它是null。提前致谢。

1 个答案:

答案 0 :(得分:0)

它不是最后的,它实际上是文件的不同执行。

当您提交表单时,您的文件会再次被调用,并且没有post_id参数,因此$ _GET ['post_id']会在文件开头的赋值中返回一个空值。

尝试向表单添加隐藏字段,或将操作更改为

post.php?post_id=<?php $_GET['post_id'] ?>

因此,您不会在提交表单后丢失该值。