douqian1517 2014-07-09 10:33
浏览 22
已采纳

使用第一个表ID将数据插入2个表中

I've two tables in my joomla 2.5 site component that trying to inset two tables and first table ID should be second table foreign-key.

Table: MYTABLE
-------------------------------------------------------------
|  mytab_id  |  mytab_name | mytab_country  |  mytab_city  |  
-------------------------------------------------------------

 Table: YOURTABLE
    -------------------------------
    |  yourtab_id  |  group_name | 
    -------------------------------

mytab_id is auto increment value and that should insert to second table yourtab_id as foreign-key.

How should I insert data to both tables as first table id value to second table id.

I've tried below code but it doesn't work.

$insert_query = "INSERT INTO #__mytable (mytab_name, mytab_country, mytab_city) VALUES ('". $mytab_name."',".$mytab_country.",'".$mytab_city."'); ";
    $db->setQuery( $insert_query );
    $db->query();

    $insert_query2 = "INSERT INTO #__yourtable (yourtab_id, group_name) VALUES (".LAST_INSERT_ID().", 2);";
    $db->setQuery( $insert_query2 );
    $db->query();

Thanks,

  • 写回答

2条回答 默认 最新

  • douzaoqu4447 2014-07-09 11:02
    关注

    Try This,

    In Joomla you can get the last insert id using

     $db->insertid();
    

    For details about Joomla DB Queries, Also try to use more standards in your query.

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
    
         // Insert columns.
         $columns = array('mytab_name', 'mytab_country', 'mytab_city');
         // Insert values.
         $values = array($db->quote($mytab_name), $db->quote($mytab_country), $db->quote($mytab_city));
    
        // Prepare the insert query.
        $query
             ->insert($db->quoteName('#__mytable'))
             ->columns($db->quoteName($columns))
             ->values(implode(',', $values));
    
        // Set the query using our newly populated query object and execute it.
        $db->setQuery($query);
        $db->query();
    

    You can make your query standards like here

    Hope it helps..

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法