插入来自循环的db数据(while)

时间:2014-10-16 16:40:26

标签: php loops while-loop

你好像这样的代码

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和$ surname,id = 1

我该如何解决?

1 个答案:

答案 0 :(得分:0)

以下是对您的脚本的编辑以及我可能遇到的问题:

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 /或PDO,但在大多数情况下 使用直接mysql函数的网站较旧或已经编码,因此存在 没有重做的任何变化;它做了很多工作。当你重新开始时,这是有道理的。希望能帮助到你。