Assuming that your form is correct and it is posting the values that you want to your script.
(You have sprinkled your code with echo
to ensure this is the case?)
The simplest reliable way of sending the data into a SQL statement and therefore into mysql is to use prepared statements.
Take a look here: http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
Basically you write the SQL statement without your variables in it (replaced with ?
) and then tell mysql to execute the statements with your variables later. It avoids the need to escape strings and worry about how to build things up.
As an example, you might have:
// Connect to mysql
$mysqli = new mysqli('where your server is', 'my_user', 'my_password', 'world');
// Build the initial statement - easier to read as you don't have your string concatenation here
$stmt = $mysqli->prepare( "INSERT INTO Entries (myoption1) VALUES (?)" );
// Tell mysql that the '?' should be replaced with the value in your post array
$stmt->bind_param( "s", $POST['myselectbox'] );
// Execute the statement
$stmt->execute()
Obviously you should add error handling too, but the documentation covers the basics of this.
SQL Injection
The main reason why the use of prepared statements is a good idea is that it avoids SQL injection attacks.
There are other ways round, but in my mind this is the simplest solution.
SQL Injection attacks are situations where someone attempts to change the SQL statement that is being run by "injecting" other SQL into your statement.
Using your code as an example, you may execute this statement:
$sql = "INSERT INTO Entries (myoption1) VALUES ('". $_POST['myselectbox'] ."')";
Which would normally receive (let's suggest) something like myoption1
.
This would result in the SQL being:
INSERT INTO Entries (myoption1) VALUES ('myoption1');
If someone decided to, they could send '='' OR '1'='1
This would result in the SQL being:
INSERT INTO Entries (myoption1) VALUES (''='' OR '1'='1');
Which is (obviously) very different.
Or, even worse send '=')'; DROP TABLE Entries WHERE (''='
This would result in the SQL being:
INSERT INTO Entries (myoption1) VALUES (''=''); DROP TABLE Entries WHERE (''='');
Use Prepared Statements
Simply put, but using prepared statements, you are telling mysql that what you are sending is a literal string to be used as a parameter. It can never be regarded as part of the statement itself and therefore the above is simply not possible.
Much much safer.
I hope that makes it clearer. If you want more info I suggest you research it independently...