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

时间:2016-03-23 18:55:16

标签: php mysql pdo

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

所以这是我的完整错误:

  

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

     

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

这是我的代码:

    $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 个答案:

答案 0 :(得分:2)

代码有三个问题:

  1. 如crhis85(upvote)所述,您无法绑定表名。
  2. PDO准备处理转义引号。

    VALUES('',':title',':by_information',':short',':long_information',':email',':filename',':filetarget',':filename2',': filetarget2','false'“);

  3. 这里的问题是,如果您将字符串定义为字符串(PDO::PARAM_STR),则使用单引号对引号进行双引号。而是这样做:

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

      'INSERT INTO table (title, ...'

    2. 此外,反引号(``)用于让数据库驱动程序知道您使用此值,而不是用作保留关键字。换句话说,在这个查询中完全过时了。

相关问题