【问题标题】:Insert into a db data coming from a loop (while)插入来自循环的数据库数据(同时)
【发布时间】:2014-10-16 16:40:25
【问题描述】:

你有这样的代码

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)
} 

}

它只插入他找到的第一个表中的数据,所以只有一个名字和一个姓氏,而不是所有 id=1 的 $name 和 $surname

我该如何解决它

【问题讨论】:

  • ext/mysql 已弃用。考虑切换到更新的库。
  • 我认为你应该考虑使用INSERT...SELECT而不是while循环。
  • 替换 $sql ="SELECT * FROM $tabella[$i] WHERE id='1'"; for $sql ="SELECT * FROM $tabella[$i] WHERE id=$i";
  • 谢谢...我正在考虑...但我找不到如何选择所有表的所有字段的方法。我试过 $sql="INSERT INTO Persons ( id,name,surname) SELECT '',name, surname FROM $tabella[$i]";但它不起作用

标签: php loops while-loop


【解决方案1】:

这是对脚本的编辑以及我发现的可能问题:

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
} 

}

与 cmets 核对。建议您使用 Prepared/或 PDO,但在大多数情况下 使用直接 mysql 函数的网站较旧或已经编码,所以那里 没有被重做的任何变化;它的工作量很大。当您重新开始时,这是有道理的。希望能帮助到你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2018-10-02
    • 2020-05-13
    • 2019-10-18
    • 2016-09-03
    • 1970-01-01
    相关资源
    最近更新 更多