-1

i am having a problem with my script in php/mysql. here is the error displayed by the server:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 'if exists (select * from notificacoes where uid in () order by id desc' at line 1' in C:\wamp\www\bigui\classes\Notificacoes.class.php on line 57

and here is my php code:

static function listar(){

            $strIdAmigos = Amizade::$strIdAmigos;

            $query = self::getConn()->query('select * from notificacoes where uid in ('.$strIdAmigos.') order by id desc');

            return $query->fetchAll(PDO::FETCH_ASSOC);
        }

my table in the mysql is empty, with no values. when i insert a value in it, the error goes away and everything is fine. any help?

  • 2
    What's the value of `$strIdAmigos`? How is it calculated? Because it seems to be empty from the error. – Mureinik Jan 13 '15 at 03:36
  • possible duplicate of [Syntax error due to using a reserved word as a table or column name in MySQL](http://stackoverflow.com/questions/23446377/syntax-error-due-to-using-a-reserved-word-as-a-table-or-column-name-in-mysql) – Kevin Brown-Silva Jan 13 '15 at 03:37

2 Answers2

1

If $strIdAmigos is empty, it causes syntax errors.

Before you execute this query, you should check the $strIdAmigos value whether it's empty or not to avoid this issue. Not to forget to escape the values if needed.

Raptor
  • 53,206
  • 45
  • 230
  • 366
  • it's like this $strIdAmigos = Amizade::$strIdAmigos; $query = self::getConn()->query('select * from notificacoes where uid in ('.$strIdAmigos.') order by id desc'); –  Jan 13 '15 at 03:49
  • wooah, what is `$strIdAmigos = Amizade::$strIdAmigos;`? You can post your codes by editing your question, not in comment please. – Raptor Jan 13 '15 at 03:52
0

When you run your query with nothing in the variable $strIdAmigos, it will error out.

Try initializing and/or checking your variable, $strIdAmigos, before running your query:

$strIdAmigos = "";

if (empty($strIdAmigos)) {
    /* Uh oh, throw an error */
} else {
    $query = self::getConn()->query('select * from notificacoes where uid in ('.$strIdAmigos.') order by id desc');
}

Note that if $strIdAmigos = "0" , the empty($strIdAmigos) will still evaluate to true and, hence, will NOT run the query.

karns
  • 5,391
  • 8
  • 35
  • 57