$ _GET不适用于SQL查询

时间:2016-03-24 23:49:55

标签: php html mysql

我试图在SQL查询中同时使用$_GET$_POST。以下是我的代码:

<?php
    $assignment = mysql_real_escape_string($_GET['name']);
    echo "$assignment <br>";

    if (isset($_POST['add'])) { 

        $user = $_POST['username'];
        $text = $_POST['comment'];

        $query = "INSERT INTO comments (user, text, assignment) VALUES ('$user', '$text', '$assignment')";
            mysql_query($query) or die('Error, comment failed to post');
    } 
?>

<h1>Add Comment</h1> 
<form action="log_entry.php" method="post"> 
    Name:<br/> 
    <input type="text" name="username" value="" /> 
    <br /><br /> 
    Comment:<br /> 
    <textarea style="height:200px;" type="text" name="comment" value="" ></textarea> 
    <br /><br />
    <input type="submit" name="add" value="Add Comment" />
</form>

但是,$assignment变量在查询中不起作用。在进行查询之前它被正确回显,但在INSERT完成后它在表内的值是空的。究竟是什么造成了这个?

1 个答案:

答案 0 :(得分:0)

不要尝试将GET和POST结合使用,而是使用隐藏的输入字段:

<?php
    $assignment = mysql_real_escape_string($_POST['name']); // Name is now in POST data, so swap this
    echo "$assignment <br>";

    if (isset($_POST['add'])) { 

        $user = $_POST['username'];
        $text = $_POST['comment'];

        $query = "INSERT INTO comments (user, text, assignment) VALUES ('$user', '$text', '$assignment')";
            mysql_query($query) or die('Error, comment failed to post');
    } 
?>

<h1>Add Comment</h1> 
<form action="log_entry.php" method="post"> 
    <!-- Add hidden input to carry the name -->
    <input type="hidden" name="name" value="<?php echo $_GET['name']; ?>"/>
    <!-- Rest of the form is the same -->
    Name:<br/> 
    <input type="text" name="username" value="" /> 
    <br /><br /> 
    Comment:<br /> 
    <textarea style="height:200px;" type="text" name="comment" value="" ></textarea> 
    <br /><br />
    <input type="submit" name="add" value="Add Comment" />
</form>