2013-02-19 20 views
0

我有2個表格:STD和SMS。我需要做的是從表STD中選擇結果複製到一個數組,然後將數組的每個元素插入到另一個表SMS中。如何使用從mysql_fetch_array獲取的數據在列中插入行?

這裏是我的代碼:

$query=mysql_query("Select from STD WHEre <my conditions>"); 
$result=mysql_fetch_array($query) 
foreach($result as $value) 
mysql_query("INSERT INTO SMS set SMS.column='$value'") 

它沒有更新的SMS表都沒有。有人可以有更好的主意或告訴我代碼有什麼問題嗎?謝謝。

+0

是僞代碼?因爲你不會在你的第一個查詢中選擇任何東西......並且你會更新你的SMS表中的每一行 – Najzero 2013-02-19 16:36:23

+0

不,我很抱歉。我只是忽略了自己的條件。 – Sang 2013-02-19 16:38:44

回答

0

你可以做,在短短一個查詢,使用INSERT INTO...SELECT聲明。

INSERT INTO SMS (col1, col2, ...., Coll3) 
SELECT col1, col2, ...., Coll3 
FROM STD 
+0

我不行。我可能生成的數組可能會有數百個值。 – Sang 2013-02-19 16:37:30

+1

你不需要數組來存儲這個值。 – 2013-02-19 16:38:22

+0

我的意思是,這些列對於我來說手動輸入會有很大的幫助 – Sang 2013-02-19 17:18:25

0

我想你正試圖從STD表中獲取所有行和它們插入SMS表,該表SMS定義是一樣的STD一個?

如果是的話,這應該工作:

$result = mysql_query('SELECT * FROM `STD` WHERE <my_conditions>'); 
while (($row = mysql_fetch_assoc($result)) !== FALSE) // Loop over all rows selected 
{ 
    $columns = implode(', ', array_keys($row)); // returns string of column names e.g. "col1, col2, col3" etc. 
    $values = "'" . implode("', '", array_values($row)) . "'"; // returns string of quoted values e.g. "'val1', 'val2', 'val3'" 
    mysql_query("INSERT INTO `SMS` ($columns) VALUES ($values)"); // inserts the row into the SMS database table 
} 
1

試試這個,但這將更新表中的所有值喜歡你的實際查詢確實

$query=mysql_query("Update SMS set 
    SMS.column=(Select <column_name> from STD where <my conditions> limit 1)"); 
1

您有關更新或插入數據?如果您要插入user JW already answered,否則您必須在您的更新查詢中設置條件。

$query=mysql_query("Select from STD WHEre <my conditions>"); 
$result=mysql_fetch_array($query) 
foreach($result as $value) 
mysql_query("Update SMS set SMS.column='$value' where SMS.std_id = '{$value['id']}'"); /// fieldnames are my example, You must generate Your condition.. 

或者您可以使用update from another table

相關問題