![](/img/trans.png)
[英]Using a single form inserting data into two differen tables though needing to insert last auto id from the first insert into the next
[英]Insert data into 2 tables using first table ID
我在joomla 2.5
站點組件中有兩個表,試圖插入兩個表,第一個表ID應該是第二個表foreign-key
。
Table: MYTABLE
-------------------------------------------------------------
| mytab_id | mytab_name | mytab_country | mytab_city |
-------------------------------------------------------------
Table: YOURTABLE
-------------------------------
| yourtab_id | group_name |
-------------------------------
mytab_id
是auto increment
值,應將yourtab_id
作為foreign-key
插入第二個表yourtab_id
中。
我應該如何將數據作為兩個表的第一個表ID值插入到兩個表中。
我試過下面的代碼,但它不起作用。
$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();
謝謝,
嘗試這個,
在Joomla中,您可以使用獲取最后的插入ID
$db->insertid();
有關Joomla DB查詢的詳細信息,還請嘗試在查詢中使用更多標准。
$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();
您可以像在這里這樣設置查詢標准
希望能幫助到你..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.