gpt4 book ai didi

php - $_GET 不适用于 SQL 查询

转载 作者:行者123 更新时间:2023-11-29 21:12:59 25 4
gpt4 key购买 nike

我尝试在 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 完成后表内的值是空的。到底是什么原因造成的?

最佳答案

不要尝试组合 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>

关于php - $_GET 不适用于 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36211916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com