Problems calling last entered id

Recently the following error was appearing on my site ‘max_user_connections’, after many searches I found that the problem was because of persistent database connection so I removed it from my code and it worked. Another problem has come up now, my lastInsertId() is returning 0 when I use persistent connection it works if I take it out it fails. I don’t even know what to do anymore. I’ll leave the most important parts of my code here:


public function __construct()
        $dsn = 'mysql:host='.$this->host.';dbname='.$this->bank;
        try {
            $this->dbh = new PDO($dsn,$this->user,$this->password);
            $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            print "Error!: " . $e->getMessage() . "<br/>";


public function lastId Inserted(){
        return $this->dbh->lastInsertId();

Searching for the last Id:

                            $sale_id = $this->db->lastId Inserted();
                            $data['sale_id'] = $sale_id;
                            $total = $stock->quant_product - $data['quant_sale'];

Hmm, this is a hard to debug issue because lastInsertedId() should just work.

I don’t fully understand what exactly you mean with the persistent database connection and max_user_connections error.

But if it is what I think it is: are you sure that you are calling the lastInsertedId() on the same database connection as they one you’re using to insert the record?

If the “main” context from the second snippet has it’s own database connection, but saleModel creates another database connection internally, that would explain why the first connection can’t retrieve the ID (it is tied to the second connection), and why you’d run into the max_user _connections issue (ever model and context creates a new database connection, resulting in many concurrent connections).

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.