0

I am trying to GET a user ID from the previous page and output the information onto another page and in my prepared statement I am getting an error in the prepare part of the statement. What I don't get is I have this almost exact same code on another site I have and it works perfeclty. I am stumped I have looked over all of the names in my db and everything is correct.

This is the error I am getting:

prepare() failed: 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 'group FROM users WHERE id = ?' at line 1

The line that is being mentioned is this one...

$stmt = $con->prepare("SELECT fullname, email, username, group FROM users WHERE id = ?");

This is the full prepared statement.

<?php
$con = mysqli_connect("localhost","root","","db");
/* check connection */
   if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    $stmt = $con->prepare("SELECT fullname, email, username, group FROM users WHERE id = ?");
    if ( false===$stmt ) {
  // Check Errors for prepare
  die('prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param("i", $_GET['id']);
    if ( false===$stmt ) {
      // Check errors for binding parameters
      die('bind_param() failed: ' . htmlspecialchars($stmt->error));
    }
$stmt->execute();
    if ( false===$stmt ) {
      die('execute() failed: ' . htmlspecialchars($stmt->error));
    }
    //Check errors for execute
//if(!$stmt->execute()){trigger_error("there was an error....".$con->error, E_USER_WARNING);}
$stmt->bind_result($fullname, $email, $username, $group);
$stmt->store_result();

if ($stmt->fetch()) { ?>

Am I missing something very obvious or what could be causing this?

Becky
  • 2,283
  • 2
  • 23
  • 50

1 Answers1

1

Put a backtick (grave accents `) or quotation marks (or apostrophes) around group so it looks like this `group`. It's a MySQL keyword so that's what is messing up your query. It's good practice to always do that with your column names.

chrisjacob
  • 170
  • 12
  • Why was it throwing an error and now letting is pass for only the last column name then? – Becky Jul 03 '15 at 02:54
  • Because GROUP is part of a MySQL keyword. That's why your error message starts at group. It's looking for GROUP BY. But like I said, it's good practice to put all your column names inside backticks so that you never have to worry about using a keyword. Here's a page about it https://dev.mysql.com/doc/refman/5.0/en/keywords.html – chrisjacob Jul 03 '15 at 02:56
  • I suppose technically it's a reserved word instead of a keyword, but either way it'll still cause ya problems. – chrisjacob Jul 03 '15 at 02:59
  • Thanks! I appreciate the help and advise! – Becky Jul 03 '15 at 03:00