![](/img/trans.png)
[英]How to insert two records into different tables first one with insert and then with select from the insert php mysql
[英]How to insert entries into different tables from one page?
我有一個名為4桌wheels
, tires
, oil_change
, other_servicing
。
現在,我為來汽車檢查的人准備了一份訂購單。 我想將所有這4個選項都放在一個表單中。 所以說有人來換新輪胎,而不是去輪胎,換油和其他服務,他們將把其他領域留空。 然后,您可能會有一個場景,其中所有四個字段都被填充。 那么,如何從一種表格將它們分別提交到各自的表?
該表格將提交給單個php腳本。 在php中,您必須執行4個單獨的查詢才能將數據放入正確的表中。 例如,如果您在php中有此代碼:
$wheels = $_REQUEST['wheels'];
$tires = $_REQUEST['tires'];
$oil_ch = $_REQUEST['oil_change'];
$other = $_REQUEST['other_servicing'];
mysql_query("INSERT INTO wheels (wheels) VALUES $wheels");
mysql_query("INSERT INTO tires (tires) VALUES $tires");
mysql_query("INSERT INTO oil_change (oil_change) VALUES $oil_ch");
mysql_query("INSERT INTO other_servicing (other_servicing) VALUES $other");
當然,我不知道您的表的架構,但這只是您如何將其分為4個查詢的一個示例。
但是,我建議您不要使用4個表,而只使用一個表並將每個表改為一列。 我可能不知道還有其他細節,哪些細節需要單獨的表格,但是有了您提供的信息,這似乎會更簡單。
這應該沒有任何問題。 接收表單數據的PHP頁面可以根據需要運行任意數量的查詢。 該代碼的框架類似於:
if($_POST['wheels']) { //if they filled in the field for wheels...
mysql_query("insert into wheels...");
}
if($_POST['tires']) { //if they filled in the field for tires...
mysql_query("insert into tires...");
}
if($_POST['oil_change']) { //if they filled in the field for oil_change...
mysql_query("insert into oil_change...");
}
... etc
對於每種形式,您將具有以下內容:
if($_POST['wheels']){mysql_query("INSERT INTO wheel_table (column1) VALUES (" . 'mysql_real_escape_string($_POST['wheels']) . "')")
這將檢查是否已設置form元素或具有一個值,如果已設置,則它將在相應的表中創建一個新行。
如果表單元素的名稱不是'wheels',則將$_POST['wheels']
更改$_POST['form_element_name']
;如果表的名稱不是wheel_table,則必須將其更改為相同的值列名稱。
這一切都必須包裹在一個
在表單操作中,您將指定將處理表單的php文件。
在php腳本文件中,您將測試使用表單的哪些部分並將其插入相應的表格中。
嘗試將測試和每個表的插入分開,以使您更輕松。
這可能有用
if(isset($_POST['submit'])) // assuming you have submit button with name 'submit'
{
$fields['wheels'] = isset($_POST['wheels']) ? $_POST['wheels'] : null;
$fields['tires'] = isset($_POST['tires']) ? $_POST['tires'] : null;
$fields['oil_change'] = isset($_POST['oil_change']) ? $_POST['oil_change'] : null;
$fields['other_servicing'] = isset($_POST['other_servicing']) ? $_POST['other_servicing'] : null;
$q="";
foreach($fieldsas $key=>$val)
{
if($val!==null)
{
$q="insert into ".$key." values('".mysql_real_escape_string($val)."')";
mysql_query($q);
}
}
if($q==="") echo " Please fill up at least one field !";
}
這只是核心思想,如果用戶一次提交多個字段,並且您可能需要添加其他值(即user_id),則可以使用該查詢執行多個查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.