Where is the error?

Asked

Viewed 46 times

0

I’ve reviewed this query several times but I don’t find the error.

"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 ''dbg0' (`filename`,`src`,`hash`,`time`) VALUES ('20170714214510th-freifejrfg.png' at line 1"

The PHP code is this:

private function insert_db($filename, $src, $hash) {
    try {
        $insert = $this->db->prepare("INSERT INTO :tabela (`filename`,`src`,`hash`,`time`) VALUES (:filename, :src, :hash, :time)");
        $insert->bindValue(':tabela', $this->table, PDO::PARAM_STR);
        $insert->bindValue(':filename', $filename, PDO::PARAM_STR);
        $insert->bindValue(':src', $src, PDO::PARAM_STR);
        $insert->bindValue(':hash', $hash, PDO::PARAM_STR);
        $insert->bindValue(':time', date('Y-m-d H:i:s'), PDO::PARAM_STR);
        $insert->execute();
        $this->lestId = $this->db->lastInsertId();
        if ($this->lestId > 0) {
            return TRUE;
        } else {
            $this->error = "Falha ao registrar imagem " . $insert->errorInfo();
            return FALSE;
        }
    } catch (PDOException $e) {
        $this->error = $e;
        return FALSE;
    }
}

I also made a function to return the query ready to test it:

public function sql($filename, $src, $hash) {
    $this->sql = "INSERT INTO $this->table (`filename`,`src`,`hash`,`time`) VALUES ('$filename', '$src', '$hash','".date('Y-m-d H:i:s')."')";
}

The same returned: "INSERT INTO dbg0 (filename,src,hash,time) VALUES ('20170714214510th-freifejrfg.png', '/var/www/html/mysite/img/postagens/', 'ad7473acb6a4d5135dbb0a01a649ef48','2017-07-14 21:45:10')". inserir a descrição da imagem aqui

  • 1

    I believe the problem is having a parameter for the table name, I believe it doesn’t work: https://stackoverflow.com/questions/15182910/php-pdo-bind-table-name

  • 1

    Did you notice that in the error message, in the table name, there is a simple quotation mark left over? Maybe this is the problem.

1 answer

1


Try to do so:

    $insert = $this->db->prepare("INSERT INTO $this->table (`filename`,`src`,`hash`,`time`) VALUES (:filename, :src, :hash, :time)");
    $insert->bindValue(':filename', $filename, PDO::PARAM_STR);
    ...
  • It worked, but why ?

  • php, Pdo, is not my area, but I have never seen pass the table name as the command parameter...

  • 2

    Probably because when you do the bind, PDO adds single quotes to the value and, in SQL, table name does not receive quotes. At most crases.

Browser other questions tagged

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