Page 1 of 1

What's wrong with this MySQL query?

Posted: Sat Aug 06, 2005 6:37 am
by pilau
I'm making a trivia game project, and now am working on the Admin CP.
The part I'm on now is the part where the administrator adds a question to a table on a DB:

Code: Select all

mysql_query("INSERT INTO questions (author, category, query, answer_a, answer_b, answer_c, correct) VALUES ($_POST[\'author\'], $_POST[\'category\'], $_POST[\'query\'], $_POST[\'answer_a\'], $_POST[\'answer_b\'], $_POST[\'answer_c\'], $_POST[\'correct\']");
PHP generates the following error:
Parse error: syntax error, unexpected T_BAD_CHARACTER, expecting T_STRING or T_VARIABLE or T_NUM_STRING in [filename]

Thanks.

Posted: Sat Aug 06, 2005 6:50 am
by tores
Put brackets around the variables. And data inserted to mysql should be single-quoted

Code: Select all

mysql_query("INSERT INTO questions (author, category, query, answer_a, answer_b, answer_c, correct) VALUES ('{$_POST[\'author\']}', '{$_POST[\'category\']}', '{$_POST[\'query\']}', '{$_POST[\'answer_a\']}', '{$_POST[\'answer_b\']}', '{$_POST[\'answer_c\']}', '{$_POST[\'correct\']}'");

Posted: Sat Aug 06, 2005 6:53 am
by pilau
Thanks.
Why do I need to put brackets around the variables?
And in what other cases do I need to do it? (if there are ases like that)

Posted: Sat Aug 06, 2005 7:01 am
by pilau
Your query gave an error.
I changed it to:

Code: Select all

<?php

mysql_query("
 INSERT INTO questions
  (author, category, query, answer_a, answer_b, answer_c, correct)
 VALUES (
  {$_POST['author']},
  {$_POST['category']},
  {$_POST['query']},
  {$_POST['answer_a']},
  {$_POST['answer_b']},
  {$_POST['answer_c']},
  {$_POST['correct']}

");

?>
And it didn't give an error back.

Posted: Sat Aug 06, 2005 7:02 am
by tores
You need brackets when you use a string or variable to access a array-cell or object-property.

Code: Select all

echo "{$arr['something']}";
echo "{$obj->$property}";

Posted: Sat Aug 06, 2005 7:07 am
by pilau
Oh alright got it.
So that goes for SQL queries as well.

Posted: Sat Aug 06, 2005 7:11 am
by tores
It goes for everything between double-quotes (and also backticks I think)

Posted: Sat Aug 06, 2005 8:44 am
by pilau
Backticks? What're backticks?

Posted: Sat Aug 06, 2005 8:58 am
by tores

Posted: Sat Aug 06, 2005 10:54 am
by pilau
Alright thank you.