Solution in case db_last_insert fails on you because LAST_INSERT_ID() is giving 0

Posted by: 
Dominique De Cooman

Problem: You want to know the next id for the nodes. According to drupal you should use db_last_insert('table', 'field'). It returned allways zero for me. In essence the drupal function will execute SELECT LAST_INSERT_ID() in mysql. Even when I executed this directly in phpmyadmin is still returned 0 while my nid count was 20. Read this for the mysql explaination.

What is the solution to overcome this problem use SHOW TABLE STATUS WHERE Name='node' in the returned object you 'll find the next value for the autoincrement.

In the example we want to redirect after saving the node. But in the form alter we need to know which node id will be the next.

<?php
/**
 * Implementation of hook_form_alter().
 */
function modulex_form_alter(&$form$form_state$form_id) {
  if (
$form_id == 'teaser_node_form') {
    
$status db_fetch_object(db_query("SHOW TABLE STATUS WHERE Name='node'"));
    
$path implode('/', array('node'$status->Auto_increment'nodesinblock'));
    
$form['#redirect'] = $path;
  }
}
?>

Add new comment