0

I am doing a simple database builder function that takes a question id, 4 options an id and a count variable.

All I want to do is in the foreach, take the options and carry out a mysql_query() on all the seperate options variables. As you can see I have put them in an array so I can loop through them in the foreach.

I think the $var variable i.e. the option value is chucking the error. The error mysql threw back to me is:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'option, order) VALUES ('e3397df9241278bfcad1945420398baa817acd7a', '005e913c9c1a' at line 1

Heres my code:

$question_id = $_POST['question_id'];
$option1 = $_POST['option_1'];
$option2 = $_POST['option_2'];
$option3 = $_POST['option_3'];
$option4 = $_POST['option_4'];

$vars = array($option1, $option2, $option3, $option4);

$count = 1;
foreach ($vars as $var){

    $id = sha1(microtime());
    echo "ID: ".$id."<br/>Q ID: ".$question_id."<br/>Option: ".$var."<br/>Order: ".$count."<br/><br/>";

    $result = mysql_query("INSERT INTO question_options (id, question_id, option, order) VALUES ('$id', '$question_id', '$var', '$count') ") or die(mysql_error());
    $count++;
}

Really appreciate if you could help show me what is wrong. Cheers.

2 Answers 2

4

Order is a MySQL keyword. You need to escape it:

$result = mysql_query("INSERT INTO question_options (`id`, `question_id`, `option`, `order`) VALUES ('$id', '$question_id', '$var', '$count') ") or die(mysql_error());

Also you should take a look at MySQLi or PDO to parameterize your queries. The mysql_ functions are deprecated.

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

2 Comments

Yes, lifesavers, not a clue that they were keywords, thanks, i'll keep keywords in mind from now on! Thanks Again!
plus, yes i've used pod and mysqli, keep it in mind, and probably convert soon
2

The terms option and order are special names for MySQL.

Use the following statement instead:

$result = mysql_query("INSERT INTO question_options (id, question_id, `option`, `order`) VALUES ('$id', '$question_id', '$var', '$count') ") or die(mysql_error());

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.