簡體   English   中英

未定義的方法PDO lastInsertId

[英]undefined method PDO lastInsertId

我有一個插入查詢,我想從表中獲取ID。 我一直在搜索,並且找到了PDO的lastInsertId()。 當我想使用它時,出現PHP錯誤。

這是我的代碼:

$db = new database();
$naam = $db->quoteQuery($_POST['naam']);
$barcode = $db->quoteQuery($_POST['barcode']);
$sql = "INSERT INTO products(name, barcode) VALUES (".$name.",".$barcode.")";
$results = $db->executeQuery($sql);
$lastid = $results->lastInsertId();

但這給出了錯誤,這是一個:

Fatal error: Call to undefined method PDOStatement::lastInsertId() in /home/onlineweuh/domains/onlinewebapps.nl/public_html/vsb/admin/add-product.class.php on line 297

我的數據庫類:

    class database 
{
    private $handleDB;
    public function __construct()
    {
        $host = ;
        $user = ;
        $database = ;
        $password = ;
        try
        {
            $this->handleDB = new PDO('mysql:host='.$host.';dbname='.$database, $user, $password);
        }
        catch (PDOException $e)
        {
            print_r($e);
        }

        $this->handleDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    }

我希望有人可以幫助我解決它,我想要在插入查詢中給出的ID。

您從PDO對象而不是結果對象獲取lastinsertid。

試試$db->lastInsertId()

在下面編輯。

您的數據庫類正在封裝handleDB / PDO對象。 由於handleDB變量是私有的,因此您不能在類外部訪問此變量。 您可能需要像這樣公開發布;

class database 
{
    public $handleDB;
    public function __construct()
    {
        $host = 'removed';
        $user = 'removed';
        $database = 'removed';
        $password = 'removed';
        try
        {
            $this->handleDB = new PDO('mysql:host='.$host.';dbname='.$database, $user, $password);
        }
        catch (PDOException $e)
        {
            print_r($e);
        }

        $this->handleDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    }

}

現在您可以調用$db->handleDB->lastInsertId();

或者,您可以將handleDB->lastInsertId()公開為類似以下功能:

class database 
{
    private $handleDB;
    public function __construct()
    {
        $host = 'remove';
        $user = 'removed';
        $database = 'removed';
        $password = 'removed';
        try
        {
            $this->handleDB = new PDO('mysql:host='.$host.';dbname='.$database, $user, $password);
        }
        catch (PDOException $e)
        {
            print_r($e);
        }

        $this->handleDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    }

    public function lastInsertId(){
        return $this->handleDB->lastInsertId();
    }

}

您將使用$db->lastInsertId();調用$db->lastInsertId();

lastInsertIdPDO的方法,不是PDOStatement 因此:

$db->lastInsertId();

您的數據庫類需要通過擴展PDO成為PDO的子類

class database extends PDO

這樣子對象就可以使用PDO中的所有方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM