First things first!
As some have mentioned already mentioned, you have a sql injection vulnerability in your code. Instead of fixing it in your code, I think it's more helpful to read:
How can I prevent SQL injection in PHP? I could fix this code for you, but since it's such a common error (#1 in the OWASP top 10) it would do your future code much good if you understood the problem.
Your question
The problem im having is that everything is being inserted into the db table apart from '$Q2' which is so strange, and i cant seem to find the problem. The HTML is below;
I think isset($_POST['submit'])
is false. And every $Q...
is assigned a value from $_POST apart from the $Q2
, because its assignment is conditional. It only happens if (isset($_POST['submit']))
How if
works
As advertised in PHP only the single one statement directly following the if
is conditional.
if ( isset($_POST['submit']) )
$Q2 = $_POST['Q2']; #this statement is conditional
$Q3 = $_POST['Q3']; #this one isn't
$Q4 = $_POST['Q4'];
$Q5 = $_POST['Q5'];
$Q6 = $_POST['Q6'];
#if there is no submit in $_POST, $Q2 is still uninitialized
#insert using $Q2, $Q3, $Q3 etc.
You can group several statements into one with curly braces {}
. You probably intend to only do the the whole insertion block conditionally:
if ( isset($_POST['submit']) ) { # { starts the conditional statement group
$Q2 = $_POST['Q2'];
$Q3 = $_POST['Q3'];
$Q4 = $_POST['Q4'];
$Q5 = $_POST['Q5'];
$Q6 = $_POST['Q6'];
#insert using $Q2, $Q3, $Q3 etc.
} # } ends the statement group
Note that I used indentation to clearly convey the block of the if-statement. Some nicely designed (as opposed to organically grown) languages use indentation as part of the syntax of grouping statements.
Your HTML
The reason why $_POST['submit']
is not set, is probably, because it isn't given a value in your form. You could try setting the name
-attribute on the <input>
of your submission button.
<input type="submit" name="submit" />
Making PHP more helpful
PHP could have helped you point to the error in your code. You used the $Q2 variable in the insert code uninitialized. This should be an error and, to paraphrase the Zen of Python:
Errors should never pass silently.
Unless explicitly silenced.
Especially during development you should set your error_reporting to something strict, like E_ALL.