-1

I have this form

<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>

and I want to store the data from my form into a table in my database.

My INSERT INTO code is this...

<?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')";
}

?>

What I am doing wrong and it does not store the data in my database. My database table is the below...

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;
Waaaaat
  • 634
  • 3
  • 14
  • 29

2 Answers2

2

Issue 1. Your form doesn't have an input named "username". So your if(isset($_POST['username'])) will never match. If you expect a username from the form you'll need to make one. If the session is set and correct (which it sounds like it is) use it. Issue 2. The connection isn't being used in the query (as the question stated). Here's updated navjot answer.

<?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());
   }
}
?>

Issue 3. This was SQL injectible, never trust user input. Issue 4. mysql functions are out of date you should switch over to mysqli or pdo.

There's tons of other threads on these topics though.

If you sanitize the username when you store it to the session that might be fine without the real escape.

chris85
  • 23,846
  • 7
  • 34
  • 51
1

You need to execute query. try this

 <?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());
        }

        ?>
Navjot Singh
  • 514
  • 4
  • 14