Skip to main content
November 18, 2009
Answered

SQL Statement Error

  • November 18, 2009
  • 1 reply
  • 519 views

Hello All,


I have the following bit of code:

if(isset($_GET['record'])){
    $recordEdit = TRUE;
    $sql = "SELECT * FROM headlines WHERE Index =?"
   
    $stmt = $dblink->stmt_init();
    if ($stmt->prepare($sql)){
        $stmt->bind_param('i',$_GET['record']);
        $stmt->bind_result($index,$date,$headline,$description,$newsType,$link);
        $stmt->execute();
        $stmt->fetch();

}

my code fails at the $stmt->prepare($sql) with the following 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 =?'

How come my sql is not initializing correctly?  I want to bind it to parameter $_Get['record'], which if I echo to the screen, is correct.

This topic has been closed for replies.
Correct answer David_Powers

OMG, it has taken ages for the penny to drop. There's nothing wrong with your basic syntax, but "Index" should not be used for a column name because it's a reserved word.

The best solution is to rename the Index column to something like id or article_id. Alternatively, you need to surround any reserved words in backticks:

 $sql = "SELECT * FROM headlines WHERE `Index` =?";

You can find a full list of MySQL reserved words here: http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html.

1 reply

David_Powers
Inspiring
November 18, 2009

PHE Admin wrote:


    $sql = "SELECT * FROM headlines WHERE Index =?"
   
    $stmt = $dblink->stmt_init();

There's no semicolon at the end of the line that defines the $sql variable. It should be this:

    $sql = "SELECT * FROM headlines WHERE Index =?";
November 19, 2009

I don't know why it wasn't in the post, but I do have the semi-colon there.  I can't figure this one out at all.

David_Powers
David_PowersCorrect answer
Inspiring
November 19, 2009

OMG, it has taken ages for the penny to drop. There's nothing wrong with your basic syntax, but "Index" should not be used for a column name because it's a reserved word.

The best solution is to rename the Index column to something like id or article_id. Alternatively, you need to surround any reserved words in backticks:

 $sql = "SELECT * FROM headlines WHERE `Index` =?";

You can find a full list of MySQL reserved words here: http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html.