我有这个表单
<form method="post" action="new_announcement.php">
<fieldset>
<legend>Create New Announcement</legend>
Subject :<input type="text" style="float-offset: !important;" name="subject" required="required" /><br>
Content :<br />
<textarea rows="10" cols="60" name="content"></textarea> </br></br>
<input type="submit" value="Upload"/>
</fieldset>
</form>
我想把表单中的数据存储到数据库中的一个表中。
我的INSERT INTO代码是这样的。。。
<?php
include_once 'header.php';
$username = $_SESSION["username"];
if(isset($_POST['username']))
{
$subject = $_POST['subject'];
$content = $_POST['content'];
$sqlinsert = "INSERT INTO announcements (author,subject,content) VALUES ('$username','$subject','$content')";
}
?>
我做错了什么,它没有将数据存储在我的数据库中。我的数据库表如下。。。
CREATE TABLE announcements
(
id INT UNSIGNED AUTO_INCREMENT,
author varchar(200),
subject varchar(200),
content varchar(3000),
timestamp int(11) unsigned not null,
PRIMARY KEY (id,author)
) ENGINE=MyISAM;
第1期。您的表单没有名为"username"的输入。所以你的if(isset($_POST['username']))
永远不会匹配。如果你希望从表单中获得用户名,你需要制作一个。如果会话设置正确(听起来确实如此),请使用它。问题2。该连接未在查询中使用(正如问题所述)。这是最新的navjot答案。
<?php
include_once 'header.php';
$username = mysql_real_escape_string($_SESSION["username"]);
if(!empty($_POST)){
if(isset($username)) {
$subject = mysql_real_escape_string($_POST['subject']);
$content = mysql_real_escape_string($_POST['content']);
$sqlinsert = "INSERT INTO announcements (author,subject,content) VALUES ('$username','$subject','$content')";
$execute = mysql_query($sqlinsert) or die(mysql_error());
}
}
?>
问题3。这是SQL可注入的,从不信任用户输入。问题4。mysql函数已经过时,您应该切换到mysqli或pdo。
不过,关于这些话题还有很多其他的线索。
如果在将username
存储到会话时对其进行消毒,那么在没有真正转义的情况下可能会很好。
您需要执行查询。试试这个
<?php
include_once 'header.php';
$username = $_SESSION["username"];
if(isset($_POST['username']))
{
$subject = $_POST['subject'];
$content = $_POST['content'];
$sqlinsert = "INSERT INTO announcements (author,subject,content) VALUES ('$username','$subject','$content')";
$execute = mysql_query($sqlinsert) or die(mysql_error());
}
?>