如何在循环中使用$ mysqli->结果?

时间:2012-03-24 05:46:40

标签: php mysql select mysqli

我正在处理从表中检索的数据

<?php
    $result=$mysqli->query("SELECT value1, value2 FROM table1");
        while($row=$result->fetch_assoc())
        {
            $value1 =   $row['valu1'];
            $value2 =   $row['value2'];

            $mysqli->query("INSERT IGNORE INTO table2 (value1) VALUES ('$value1')");
            $result2    =   $mysqli->query("SELECT id FROM table2 WHERE value1='$value1'");
            $row2       =   $result2->fetch_assoc();
            $column1_id =   $row2['id'];
            $result2->close();

            $mysqli->query("INSERT IGNORE INTO table3 (value2) VALUES ('$value2')");
            $result3    =   $mysqli->query("SELECT id FROM table3 WHERE value1='$value2'");
            $row3       =   $result3->fetch_assoc();
            $column2_id =   $row3['id'];
            $result3->close();

            $mysqli->query("INSERT INTO table4 (value1,value2) VALUES ('$value1','$value2')");
        }
?>

问题是,子$result将与父项混淆,而while循环只能在第一个循环中运行。

1 个答案:

答案 0 :(得分:0)

更好的应该是这样的

insert ignore into table2 (value1) select value1 from table1;
insert ignore into table3 (value2) select value2 from table1;
insert ignore into table4 (value1, value2) select value1, value2 from table1

这是优化的,我认为你需要SELECT id ..和loop
(我看到你在你的例子中使用了结果)