0

I am getting a syntax error after I added another value to be added to the data base. I have no idea what is the problem I'm kinda new to php and mysql. what am i doing wrong?

ERROR: 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 ''index',name,score) VALUES ('2','guyaa','300')' at line 1

this is the insert php:

<?php
require_once 'app_config.php';
connect();

$index = $_GET['index'];
$name = $_GET['name'];
$score = $_GET['score'];

$query = "INSERT INTO scores (index,name,score) VALUES ('" . $index ."','" . $name ."','" . $score . "')";
$result = mysql_query($query) or die('ERROR: '. mysql_error());

and this is the retrieve :

<?php
require_once 'app_config.php';
connect();

$query = "SELECT * From scores";
$result = mysql_query($query);
while($item = mysql_fetch_array($result)){
echo $item['index'];
echo ' - ';
echo $item['name'];
echo ' - ';
echo $item['score'];
echo '<br>';
}
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Guy Hezi
  • 5
  • 2
  • looks fine, so print your query here.. with real values and error code.. – Naruto Aug 03 '15 at 14:45
  • Also note that mysql_ is deprecated. http://stackoverflow.com/questions/8891443/when-should-i-use-mysqli-instead-of-mysql – Matheno Aug 03 '15 at 14:49
  • 2
    `index` is a MySQL reserved word - https://dev.mysql.com/doc/refman/5.5/en/keywords.html - so it needs to be wrapped with backticks - `\`index\`` -> `$query = "INSERT INTO scores (\`index\`,name,score) VALUES ...` – Sean Aug 03 '15 at 14:52
  • i change to this : $query = "INSERT INTO scores ('index',name,score) VALUES ('" . $index ."','" . $name ."','" . $score . "')"; and added brackets and i still got the error :( – Guy Hezi Aug 03 '15 at 15:03
  • (1) you used single quotes `'` **not** backticks `\``. quotes are used for string values, backticks are used for identifiers. (2) It is common courtesy on SO that if you have an error message that you include it in your question. Without the error message you are assuming we are mind readers, and basically wasting everyone's time. – Sean Aug 03 '15 at 15:09
  • thanks guys i was need to add brackets so i added ' but thats not good i needed to add ` instead when i used index.... thanks :) – Guy Hezi Aug 03 '15 at 15:15
  • Always use backticks for field names – Raymond Ativie Aug 05 '15 at 15:18

1 Answers1

1

Index is a MySQL reserved word. You need to use backticks

$query = "INSERT INTO scores (`index`,name,score) VALUES ('" . $index
."','" . $name ."','" . $score . "')";
ThomasVdBerge
  • 7,483
  • 4
  • 44
  • 62