致命错误:未捕获异常';PDOException';带有消息';SQLSTATE[42000]


Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]

我正在从普通SQL迁移到PDO,因为我让我的一个朋友测试我是否有弱点,他建议我使用PDO,他发现了很多弱点。

这是我的全部错误:

致命错误:未捕获异常"PDOException",消息为"SQLSTATE[42000]":语法错误或访问冲突:1064您的SQL语法有错误;查看与MySQL服务器版本对应的手册,了解在第54行的"in/home/ubuntu/workspace/post.php"附近使用的正确语法

(!)PDOException:SQLSTATE[42000]:语法错误或访问冲突:1064您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,了解在"?"附近使用的正确语法?(idtitleinfo_bysinfo_shortsinfo_longsemail,位于第54行/home/ubuntu/workspace/post.php中的第1行

这是我的代码:

    $stmt = $db->prepare("INSERT INTO  :portal
    (`id`, `title`, `info_bys`, `info_shorts`, `info_longs`, `email`, `filename`, `filepath`, `filename2`, `filepath2`, `approved`) 
    VALUES ('', ':title', ':by_information', ':short', ':long_information', ':email', ':filename', ':filetarget', ':filename2', ':filetarget2',  'false'");
    $stmt->execute(array(':portal' => $portal, ':title' => $title, ':by_information' => $by_information, ':short' => $short, ':long_information' => $long_information, ':email' => $email, ':filename' => $fileName, ':filetarget' => $fileTarget, ':filename2' => $fileName2, ':filetarget2' => $fileTarget ));
    echo $affected_rows.' were affected';

是不是有一些我不能在PDO中使用的东西可以在SQL中使用,还是我只是键入了错误的东西。

希望有人能帮忙。

编辑:

新代码:

    function buildQuery( $get_var ) 
{
    switch($get_var)
    {
        case 1:
        $portal = $_POST['portal'];
            break;
    }
                $stmt = $db->prepare("INSERT INTO  :portal
            (`id`, `title`, `info_bys`, `info_shorts`, `info_longs`, `email`, `filename`, `filepath`, `filename2`, `filepath2`, `approved`) 
            VALUES (:title, :by_information, :short, :long_information, :email, :filename, :filetarget, :filename2, :filetarget2,  'false'");
            $stmt->execute(array(':portal' => $portal, ':title' => $title, ':by_information' => $by_information, ':short' => $short, ':long_information' => $long_information, ':email' => $email, ':filename' => $fileName, ':filetarget' => $fileTarget, ':filename2' => $fileName2, ':filetarget2' => $fileTarget ));
            echo $affected_rows.' were affected';
}

代码的三个问题:

  1. 正如crhis85(upvote)所说,您不能绑定表名
  2. PDO prepare负责转义引号。

    VALUES(",":title","by_information",":short",",long_information",";email',":filename',":filetarget2","false");

这里的问题是,如果您为字符串(PDO::PARAM_STR)定义了一个参数,那么这些值将用单引号双引号引起来。相反:

`VALUES ('', :title, :by_information, :short, ....");`
  1. 不要插入ID,这应该设置为自动递增,并且是自动完成的。

    'INSERT INTO table (title, ...'

此外,backticks(``)用于让数据库驱动程序知道您正在使用此值,并且不能用作保留关键字。换句话说,在这个查询中完全过时了。

相关文章: