What’s wrong with this query?

Asked

Viewed 56 times

1

I have a Dbupdate function that updates the data in the database. This function creates a query based on the array passed as parameter.

For example, if I send this array (like $visit)

  'ips' => '192.168.25.1, 127.0.0.1'
  'real' => 1
  'last' => '2017-05-19 18:15:50'
  'desktop' => 10

When executing DBExecute('clientes', $visit, 'country = pt_BR') this query is returned to me:

UPDATE ac_analytics SET ips = '192.168.25.1, 127.0.0.1', real = '1', last = '2017-05-19 18:15:50', desktop = '10' WHERE country = 'pt_BR'

And then I get sql 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 'real = '1', last = '2017-05-19 18:15:50', desktop = '10' WHERE country = 'pt_BR'' at line 1

My full update function:

//Altera registros
function DBUpdate($table, array $data, $where = null){
    foreach ($data as $key => $value) {
        $fields[] = "{$key} = '{$value}'";
    }

    $fields = implode(', ', $fields);

    $table = DB_PREFIX.'_'.$table;
    $where = ($where) ? " WHERE {$where}" : null;

    $query = "UPDATE {$table} SET {$fields}{$where}";
    return DBExecute($query); // Função de execução de queries
}
  • @Knautiluz Exactly what I needed. I will change the name of the tables... Thank you.

  • You do not need to change the name of the tablets. Use the escape character (crase). Example: ips, ac_analytics, last and so on. It’s always good to use it because Mysql and other SGDB have many reserved words and time or other you will run into them.

1 answer

1

With the comment of a user (who, for some reason, deleted the comment) I was able to detect the problem. My query had words reserved by Mysql, in which I had 2 options:

  • Change table name to a name not reserved by the system. You can check on this link.
  • Use escape characters in my query. ` ips ` = '192.168.25.1, 127.0.0.1'
  • Sorry Daniel, I deleted the comment because I was not able to put the crase because the stack identified as code and I had to leave.

  • 1

    @Knautiluz I imagined. If you want to add crase, use ASCII & #96 ; and spaces. Better stack support is missing for this haha situation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.