Search code examples
phpmysqlphp-5.3mysql-insert-id

mysql_insert_id() stopped working after PHP update


I am preparing to update a live web server from PHP 5.2.12 to 5.3.5. In preparation, I have performed the update on a second server which is a mirror of the live one ("dev" server). Both servers are using FreeBSD, and both used ports to install PHP and MySQL. The live server is using MySQL 5.0.89, the newly upgraded dev server is using 5.1.54.

The following code executes as expected on the live server (PHP 5.2.12/5.0.89), returning the value of the AUTO_INCREMENT row that was just inserted. This function is part of a database class that is used throughout the site, where "$this->_private['cn']" is the resource link.

 public function insert ($sql=false) {
    @mysql_select_db($this->_private['db_name'],  $this->_private['cn']);
    $res = null;            
    if (false !== $sql) {
        $query_obj = mysql_query($sql, $this->_private['cn']);
        if ($query_obj)
            $res = mysql_insert_id($this->_private['cn']);
    }
    return $res;
}

On the dev server (5.3.5/5.1.54), the return is zero. Note - not null (which is returned if the query fails), but ZERO. I can look at the table and verify that a new row has in fact been inserted, and the auto increment field has properly advanced. The field value is currently at 121288, so it is well within PHP's integer range. I've even re-created the class's code on a simple page and get the same result. mysql_error() indicates no failures. Error reporting is set to E_ALL, not a peep there.

ARGH! Any ideas?


Solution

  • see this bug which recommends following your query with SELECT LAST_INSERT_ID()