2014-10-16 66 views
0

喜來有這樣插入到數據庫中的數據從一個循環(同時)

for ($i=0; $i<=count($query)+1 ; $i++) 
{ 
$sql ="SELECT * FROM $tabella[$i] WHERE id='1'"; 
$result=mysql_query($sql); 
$numrows=mysql_num_rows($result); 

while($row = mysql_fetch_array($result)) 
{ 
$name=$row['name']; 
$surname=$row['surname']; 

INSERT INTO student (name,surname) Values ($name,$surname) 
} 

} 

代碼,只從他找到的第一個表中插入數據,所以只有一個名字和一個姓,而不是全部$ name和$姓與ID = 1

我怎樣才能解決這個問題

+0

ext/mysql已棄用。考慮切換到一個更新的庫。 – Gordon 2014-10-16 16:42:02

+1

我認爲你應該考慮使用[INSERT ... SELECT](http://dev.mysql.com/doc/refman/5.1/en/insert-select.html)而不是while循環。 – 2014-10-16 16:51:52

+0

替換$ sql =「SELECT * FROM $ tabella [$ i] WHERE id ='1'」; for $ sql =「SELECT * FROM $ tabella [$ i] WHERE id = $ i」; – kraysak 2014-10-16 16:52:09

回答

0

下面是編輯你的腳本和可能出現的問題我fouund:

for ($i=0; $i<=count($query)+1 ; $i++)   //Why is there a +1? 
{ 
$sql ="SELECT * FROM $tabella[$i] WHERE id='1'"; //Your issue could be here, tabella[$1] 
$result=mysql_query($sql);      //may not be totally there 
$numrows=mysql_num_rows($result);    //Try to echo your SELECT $sql query 
               //to check 

               //Why do you have $numrows? I dont see 
               //that being used anywhere 

while($row = mysql_fetch_array($result)) 
{ 
$name=$row['name']; 
$surname=$row['surname']; 

INSERT INTO student (name,surname) Values ($name,$surname) //Your INSERT statement 
                  //looks ok 
                  //Try to use single/or double 
                  //quotes around the values 
                  //I like having `name`, 
                  //`surname` around fields 
} 

} 

查看此評論。建議您使用Prepared/or PDO,但在大多數情況下,使用直接mysql功能的網站 較舊或已編碼,因此 並不是重做的任何更改;它的很多工作。當你開始新鮮時,這很有意義。希望能幫助到你。

相關問題