db_last_insert_id() 获取最后插入ID
db_last_insert_id($table,$field)返回最后插入的ID . 这个函数是线程安全的 . 其中包含两个参数 $table (表名) , $field (表的自动增长字段名) .
说说我是怎么用到这函数的吧 , 在表安装时插入一些默认的数据 , 这时候需要在 .install 文件中的 hook_install() 函数内执行插入语句 , 当然一定要在 drupal_install_schema()函数后 , 添加执行数据库操作语句 db_query() , 也就是插入记录 (insert 语句) .
下面操作时真的两个有关联关系的表进行数据插入 :
<?php
/**
* Implementation of hook_install()
*/
function demo_install(){
drupal_install_schema('demo');
/*
* parent_category
*/
$category[0] = 'Animal';
db_query("INSERT INTO {parent_category} (category_name) VALUES('".$category[0]."');");
$parent_id[0] = db_last_insert_id('parent_category','category_id'); //调用db_last_insert_id($table,$field)函数
/*
* $children_category
*/
$children_category[0] = 'Birds';
$children_category[1] = 'Beasts';
$children_category[2] = 'Fish';
$children_category[3] = 'Insects';
$children_category[4] = 'Reptiles';
$children_category[5] = 'Amphibians';
foreach($children_category as $row) {
$data['parent_category_id'] = $parent_id[0];
$data['children_category_name'] = $row;
$data['created'] = time();
$insert ="INSERT INTO {children_category} (parent_category_id,children_category_name,created) VALUES(".$data['parent_category_id'].",
'".$data['children_category_name']."',".$data['created'].")";
db_query($insert);
}
}
?>
- 添加新评论
- 361 次点击
评论
php
真是强大,看不懂