调用未定义的方法Database :: lastInsertId()

时间:2015-12-07 17:44:07

标签: php sql pdo

我想插入像Worpdress

这样的帖子

我使用lastInsertId()获取id_post,但我收到了错误消息:Call to Undefined method Database::lastInsertId()

这是我的代码

http://pastebin.com/UzaQBNnU

public function savePosts()
{
    $sql = "INSERT INTO artikel (id_artikel, judul_artikel, isi_artikel, status, categories) 
            VALUES (NULL, :judul_artikel, :isi_artikel, 'save', :categories_artikel)";
    $stmt = Database::prepare($sql);
    $stmt->bindParam(':judul_artikel', $this->judul_artikel);
    $stmt->bindParam(':isi_artikel', $this->isi_artikel);
    $stmt->bindParam(':categories_artikel', $this->categories_artikel);
    $stmt->execute();
    return Database::lastInsertId();
}

http://pastebin.com/gmj5djgv

<?php 

//konstanta Database
define('host', 'localhost');
define('user', 'root');
define('pass', '');
define('db_name', 'cms');


//class Database
class Database
{
    private static $cms;

    public static function getCMS()
    {
        if(!isset(self::$cms)) {
            try {
                self::$cms = new PDO('mysql:host='.host. ';dbname='.db_name, user, pass);
                self::$cms->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                self::$cms->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
            }
            catch(PDOException $exception) {
                echo $exception->getMessage();
            }
        }
        return self::$cms;
    }

    public static function prepare($sql)
    {
        return self::getCMS()->prepare($sql);
    }
}

?>

1 个答案:

答案 0 :(得分:0)

几乎是肖恩所说的。您对Database::lastInsertId()的调用会引发未定义方法错误,因为您尚未定义方法Database::lastInsertId()。您需要将定义添加到Database类,与prepare()相同:

public static function lastInsertId()
{
    return self::getCMS()->lastInsertId();
}

根据数据库驱动程序如何(或是否)实现PDO::lastInsertId(),即使这可能也可能不起作用。