Search code examples
phpmysqliprepare

insert_id is keep saying 0


goodday.

I've a class called nieuws and i want to created a function that insert a record into the database. After that i need that id of the created record for something else so I sawon the internet that $...->insert_id has to give the id of the last created record in that table. But that did not work by me.

Anyone know what is wrong here?

$sql = "INSERT INTO nieuws (`id`, `titel`, `datum`, `gebruikerId`, `text`) VALUES (NULL, ?, ?, ?, ?)";
    if ($datum = $this->_db->prepare($sql)) {
        $datum->bind_param("siis", $this->_title, $this->_date, $this->_gebruikerId, $this->_tekst);
        $datum->execute();
        $this->_id =  $datum->insert_id;
        //$this->addRssNieuws();
    }

Solution

  • The insert_id is an attribute of the connection, not the statement.

    $this->_id =  $this->_db->insert_id;
    

    should work.