0

I have the following codes:

   $query = "INSERT INTO main_table (id, matric_no, session, semester, 
                                    course_name, test, exam,practical)
       VALUES (NULL, '$_POST[matric_no]', '$_SESSION[session]', 
              '$_SESSION[semester]', '$_SESSION[course_name]', '$_POST[test]',
              '$_POST[exam]', '$_POST[practical]')";

       mysql_query($query) or
       die (mysql_error());

Then I tried:

       echo "$_POST[semester]";
       echo "$_POST[course_name]" ;

and they echoed out what I was expecting but not INSERTing INTO the database.. Only those two.

Thanks.

4
  • What types are the columns? Also, never insert POST values directly. See php.net/manual/en/security.database.sql-injection.php Commented Nov 21, 2011 at 23:03
  • what exactly do you mean by columns? The first session value inserted. Commented Nov 21, 2011 at 23:05
  • What types are the database fields Commented Nov 21, 2011 at 23:06
  • yes i can see the mistake. I used INT instead of VARCHAR... Thanks a bunch. Commented Nov 21, 2011 at 23:09

2 Answers 2

2

As pointed out in the comments, the problem was a column type mismatch that wasn't visible in the original question.

However, it is a very bad idea to insert POST or other values directly - always run mysql_real_escape_string() (or whatever sanitation function your database library provides) on them. More on SQL injections here.

Sign up to request clarification or add additional context in comments.

3 Comments

@Martin I only answered it because there was no correct one to tick - I initially suggested deleting the question altogether.
ah, I have meant "Why did you mark this as community wiki answer?", sorry.
@Martin yeah, I understood what you meant. No specific reason, I was just annoyed about the existing answers (one of which was accepted) so I chose to shove one in for accepting. It wouldn't have had to be CW though.
-1

This code should give you a syntax error...

   echo "$_POST[semester]";
   echo "$_POST[course_name]" ;

Try this

   echo "{$_POST['semester']}";
   echo "{$_POST['course_name']}" ;

or this:

   echo "xxx".$_POST['semester']."xxx";
   echo "xxx".$_POST['course_name']."xxx;

More information here:

Mind that $_POST[xxx] is note the proper syntax !!! Read docs above!

3 Comments

Not true. This is proper syntax to address an array inside a string.
Peter - have you tried echo "$_POST[semester]";? It works. It's not the problem (although examples 2 and 3 are much better style, no doubt)
... but removing downvote because it's still way better than the other one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.